const { spawn } = require('child_process') let pidMap = {} /** * options: { onSuccess: null | function, onError: null | function, onClose: null | function } */ function start(command, args, options = {}) { const childProgress = spawn(command, args) pidMap[childProgress.pid] = childProgress const promise = new Promise((resolve, reject) => { childProgress.stdout.on('data', data => { resolve(data.toString()) }) childProgress.stderr.on('data', data => { reject(data.toString()) }) }) /** childProgress.on('close', code => { options.onClose && options.onClose(code) }) */ return { pid: childProgress.pid, promise } } function kill(pid) { const childProgress = pidMap[pid] let status = false if (childProgress && !childProgress.killed) { status = childProgress.kill() } childProgress = null delete pidMap[pid] return status } module.exports = { start, kill, }