UNPKG

@bleed-believer/path-alias

Version:
52 lines (51 loc) 1.71 kB
import { fileURLToPath, pathToFileURL } from "url"; import { isAbsolute, join, resolve } from "path"; import { spawn } from "child_process"; export class NodeLauncher { static #loaderPath = process.platform === 'win32' ? pathToFileURL(join(fileURLToPath(import.meta.url), '../../../index.js')).href : join(fileURLToPath(import.meta.url), '../../../index.js'); static get loaderPath() { return NodeLauncher.#loaderPath; } #targetPath; get targetPath() { return this.#targetPath; } #targetArgs; get targetArgs() { return this.#targetArgs.slice(); } #process; #spawn; constructor(targetPath, targetArgs, inject){ this.#process = inject?.process ?? process; this.#spawn = inject?.spawn ?? spawn; this.#targetPath = !isAbsolute(targetPath) ? resolve(this.#process.cwd(), targetPath) : targetPath; this.#targetArgs = targetArgs; } initialize(watch) { return new Promise((resolve, reject)=>{ try { const args = [ '--import', NodeLauncher.loaderPath, this.#targetPath, ...this.#targetArgs ]; if (watch) { args.unshift('--watch'); } const proc = this.#spawn('node', args, { stdio: 'inherit' }); proc.on('close', (___)=>{ resolve(); }); proc.on('error', (err)=>{ reject(err); }); } catch (err) { reject(err); } }); } }