UNPKG

nsolid-manager

Version:

A manager that sets up and runs N|Solid for you

68 lines (54 loc) 1.52 kB
'use strict' let processes = [] let exitCode = 0 /** * Set opts.killAll to bring down all processes if any single process dies. */ module.exports.killOnExit = function (proc, opts) { processes.push(proc) opts = opts || {} const killAll = !!opts.killAll killOnExitSetup() proc.once('exit', code => exitCode = code ? 1 : exitCode) proc.once('error', () => exitCode = 1) proc.once('error', err => console.error(err)) proc.once('error', onEnd) proc.once('close', onEnd) function onEnd () { processes = processes.filter(p => p.pid !== proc.pid) if (killAll) cleanupAndExit() } } function killAll () { if (killAll.called) return killAll.called killAll.called = new Promise((yeah, nah) => { processes.forEach(proc => { // wait for a bit for kill then terminate const timeout = setTimeout(() => { if (proc.connected) proc.kill('SIGTERM') }, 2000) proc.once('close', () => { clearTimeout(timeout) maybeDone() }) proc.kill() }) function maybeDone () { if (processes.length) return yeah() } }) return killAll.called } function cleanupAndExit () { if (cleanupAndExit.called) return cleanupAndExit.called = true killAll().then(() => process.exit(exitCode || 0)) } function killOnExitSetup () { if (killOnExitSetup.called) return killOnExitSetup.called = true process.on('SIGINT', cleanupAndExit) process.on('SIGTERM', cleanupAndExit) process.on('beforeExit', cleanupAndExit) }