I have a node.js script that does some logging to a file using WriteStream. On certain events I want to stop execution of the script, i.e. warn to log and exit immediately after that. Being asyncronious node.js does not allow us to do it straight forward like:
#!/usr/local/bin/node
var fs = require('fs');
var stream = fs.createWriteStream('delme.log', { flags: 'a' });
stream.write('Something bad happened\n');
process.exit(1);
Instead of appending a message to delme.log this script does nothing with the file. Handling 'exit' event and flushing doesn't work. The only way to write the last log message before exitting found so far is to wrap process.exit(1) in the setTimeout():
#!/usr/local/bin/node
var fs = require('fs');
var stream = fs.createWriteStream('delme.log', { flags: 'a' });
stream.write('Something bad happened\n');
setTimeout(function(){
process.exit(1);
}, 30);
However in this form it doesn't stop the script execution immediately and the script will be running for some time after the critical event happened. So I'm wondering if there are other ways to exit a script with a log message?