Created
November 27, 2016 20:23
-
-
Save MaxySpark/f77a2b6572c46cc4ba73dc152cc5c5d7 to your computer and use it in GitHub Desktop.
run a script from under script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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