Skip to content

Instantly share code, notes, and snippets.

@joshwentz
Last active April 4, 2024 03:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshwentz/11230694 to your computer and use it in GitHub Desktop.
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
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();
}
]);
@joshwentz
Copy link
Author

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

@marcosilvestroni
Copy link

Sounds great, but the callback is compulsory or not?

@jmercouris
Copy link

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