I need to run a child process which will then run in the background; at the same time, I want to manipulate its output (adding timestamp etc.) and redirect it to specific files. At the moment I am doing this:
try {
var out = fs.createWriteStream(`${this.logdir}/${lp}-out.log`, { flags: 'a', defaultEncoding: 'utf8' } );
var err = fs.createWriteStream(`${this.logdir}/${lp}-err.log`, { flags: 'a', defaultEncoding: 'utf8' } );
} catch( e ){
console.log("Could not open log files for writing:", e );
return;
}
try {
var child = childProcess.spawn( '/usr/bin/node', [ server ], { env: env, uid: uid, gid: gid, cwd: cwd } );
} catch( e ) {
console.log("Could not run node:", e );
return;
}
child.stdout.on('data', function( data ){
try {
// The child process has stopped dealing with incoming connections.
// For all intents and purposes, the process is useless and dead
var d = data.toString();
if( data.toString().match( /^THE SERVER HAS STOPPED$/m ) ){
console.log("The child process has stopped taking connections!");
try { fs.unlinkSync( pidFile ); } catch( e ){}
dead = true;
maybeRestart();
}
var pre = (new Date()).toString() + ' [' + child.pid + '] ';
out.write( Buffer.from( data.toString().trim().split("\n").map( (l) => { return pre + l }) .join('\n') ));
} catch( e ){
console.log("Error while redirecting stream to standard output!", e );
}
});
child.stderr.on('data', function( data ){
try {
var pre = (new Date()).toString() + ' [' + child.pid + '] ';
err.write( Buffer.from( data.toString().trim().split("\n").map( (l) => { return pre + l }) .join('\n') ));
} catch( e ){
console.log("Error while redirecting stream to standard error!", e );
}
});
Questions:
- I am new to streams. Am I doing it right? If not, what's the "right" way of doing this?
- I noticed that errors within the stream's "data" callbacks do not bubble up -- not even
UnexpectedErrors, hence thetry {} catch {}statements. Was that the right way to go?
via Merc
No comments:
Post a Comment