UNPKG

@figliolia/child-process

Version:

A wrapper around the node.js spawn function providing a promise and graceful exiting

48 lines (47 loc) 1.52 kB
import { exec, spawn } from "node:child_process"; import { promisify } from "node:util"; export class ChildProcess { process; handler; static execute = promisify(exec); constructor(command, options = { stdio: "inherit" }) { const [root, args] = ChildProcess.split(command); this.process = spawn(root, args, options); this.handler = ChildProcess.promisify(this.process); } static wrapCommand(command, options = { stdio: "inherit" }) { const [root, args] = this.split(command); const CP = spawn(root, args, options); return this.promisify(CP); } static promisify(CP) { return new Promise((resolve, reject) => { CP.on("exit", code => { if (code === 1) { reject(); } else { resolve(); } }); }); } static split(command) { const [root, ...args] = command.split(" "); return [root, args]; } static get parentProcess() { return process; } static bindExits(CPs) { const NUKE = () => { CPs.forEach(CP => CP.kill()); }; this.parentProcess.on("exit", NUKE); this.parentProcess.on("SIGINT", NUKE); this.parentProcess.on("SIGQUIT", NUKE); this.parentProcess.on("beforeExit", NUKE); this.parentProcess.on("uncaughtException", NUKE); this.parentProcess.on("unhandledRejection", NUKE); } }