Skip to content

Instantly share code, notes, and snippets.

@fzn0x
Created April 10, 2022 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fzn0x/14d9c82e0f13f921052ceeb166bd7667 to your computer and use it in GitHub Desktop.
Save fzn0x/14d9c82e0f13f921052ceeb166bd7667 to your computer and use it in GitHub Desktop.
var childProcess = require('child_process');
function runScript(scriptPath, callback) {
// keep track of whether callback has been invoked to prevent multiple invocations
var invoked = false;
var process = childProcess.fork(scriptPath);
// listen for errors as they may prevent the exit event from firing
process.on('error', function (err) {
if (invoked) return;
invoked = true;
callback(err);
});
// execute the callback once the process has finished running
process.on('exit', function (code) {
if (invoked) return;
invoked = true;
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
}
// Now we can run a script and invoke a callback when complete, e.g.
runScript('./some-script.js', function (err) {
if (err) throw err;
console.log('finished running some-script.js');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment