UNPKG

@steelbrain/spawn

Version:

Process spawning APIs beautified

71 lines (70 loc) 2.66 kB
import { spawn as nativeSpawn } from 'child_process'; async function spawnInternal(command, args, options) { const spawnedProcess = nativeSpawn(command, args, options); const promise = new Promise((resolve, reject) => { const output = { stdout: spawnedProcess.stdout ? [] : null, stderr: spawnedProcess.stderr ? [] : null, }; spawnedProcess.on('error', reject); if (spawnedProcess.stdout) { spawnedProcess.stdout.on('data', function (chunk) { output.stdout.push(chunk); if (options.handleStdout) { options.handleStdout(chunk); } }); } if (spawnedProcess.stderr) { spawnedProcess.stderr.on('data', function (chunk) { output.stderr.push(chunk); if (options.handleStderr) { options.handleStderr(chunk); } }); } spawnedProcess.on('close', (code) => { let outputStdout = null; if (output.stdout != null) { outputStdout = options.encoding === null || options.encoding === 'buffer' ? Buffer.concat(output.stdout) : output.stdout.join(''); } let outputStderr = null; if (output.stderr != null) { outputStderr = options.encoding === null || options.encoding === 'buffer' ? Buffer.concat(output.stderr) : output.stderr.join(''); } resolve({ exitCode: code, stdout: outputStdout, stderr: outputStderr, }); }); }); options.handleChildProcess(spawnedProcess); return promise; } export function spawn(command, args, options) { let spawnedProcess; const promise = spawnInternal(command, args, { ...options, handleChildProcess(_spawnedProcess) { var _a; spawnedProcess = _spawnedProcess; (_a = options === null || options === void 0 ? void 0 : options.handleChildProcess) === null || _a === void 0 ? void 0 : _a.call(options, _spawnedProcess); }, }); promise.kill = function (signal) { // TODO: kill all subprocesses on windows with wmic? return spawnedProcess.kill(signal); }; return promise; } export function spawnFile(filePath, args, options) { return spawn(process.execPath, [filePath].concat(args), options); // ^ TS is drunk, force override the type }