title: What's the right way to exit node.js script with a log message?
body: <p>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:</p>
  
  <pre><code>#!/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);
  </code></pre>
  
  <p>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 <code>process.exit(1)</code> in the <code>setTimeout()</code>:</p>
  
  <pre><code>#!/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);
  </code></pre>
  
  <p>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?</p>