Last active
April 4, 2024 03:26
-
-
Save joshwentz/11230694 to your computer and use it in GitHub Desktop.
Synchronous Fork in Node.js (with async.series): wait for child_process.fork to finish, then execute part2
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 fs = require('fs'); | |
var fork = require('child_process').fork; | |
var async = require('async'); | |
async.series([ | |
function(callback){ | |
var command = fork("./command.js", [], {silent: true }); | |
command.stdout.pipe(process.stdout); | |
command.stderr.pipe(process.stderr); | |
//CREATE write file for stdout, LISTEN to stdout, WRITE to file | |
var file = fs.createWriteStream('./progress.txt'); | |
command.stdout.on('data', function(data) {file.write(data);}); | |
command.stderr.on('data', function(data) {file.write(data);}); | |
command.stdout.on('end', function(data) {file.end();}); | |
command.stderr.on('end', function(data) {file.end();}); | |
//when child process exits, check if there were any errors and close the writeable stream | |
command.on('exit', function(code) { | |
if (code !== 0) {console.log('Failed: ' + code);} | |
callback(); | |
}); | |
}, | |
function(callback){ | |
console.log('PART2'); | |
callback(); | |
} | |
]); |
Sounds great, but the callback is compulsory or not?
Unfortunately, the callback is compulsory due to the use of the async library. See the documentation here: https://caolan.github.io/async/v3/docs.html#series
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hardest Part: putting the callback(); inside the command.on 'exit' function
By doing this, the script will wait until the fork is finished before moving onto PART2
REFERENCES
https://github.com/caolan/async