title: Node.js socket.send( ) functions failing to complete before exit
body: <p>In some Node.js scripts that I have written, I notice that even if the last line is a synchronous call, sometimes it doesn't complete before Node.js exits.</p>
  
  <p>I have never seen a <code>console.log</code> statement fail to run/complete before exiting, but I have seen some other statements fail to complete before exiting, and I believe they are all synchronous. I could see why the callback of an async function would fail to fire of course in this case.</p>
  
  <p>The code in question is a ZeroMQ <code>.send()</code> call like so:</p>
  
  <pre><code>   var zmq = require('zmq');
     var pub = zmq.socket('pub');
  
     pub.bindSync('tcp://127.0.0.1:5555');   
  
      setInterval(function(){
          pub.send('polyglot');
      },500);
  </code></pre>
  
  <p>The above code works as expected...but if I remove <code>setInterval()</code> and just call it like this:</p>
  
  <pre><code>   var zmq = require('zmq');
     var pub = zmq.socket('pub');
  
      pub.bindSync('tcp://127.0.0.1:5555');
  
      pub.send('polyglot');  //this message does not get delivered before exit
      process.exit(0);
  </code></pre>
  
  <p>...Then the message will not get delivered - the program will apparently exit before the <code>pub.send()</code> call completes.</p>
  
  <p>What is the best way to ensure a statement completes before exiting in Node.js ? Shutdown hooks would work here, but I am afraid that would just be masking the problem since you can't put everything that you need to ensure runs in a shutdown hook.</p>
  
  <p>This problem can also be demonstrated this way:</p>
  
  <pre><code> if (typeof messageHandler[nameOfHandlerFunction] == 'function') {
            reply.send('Success');
            messageHandler[nameOfHandlerFunction](null, args);
           } else {
           reply.send('Failure'); //***this call might not complete before the error is thrown below.***
           throw new Error('SmartConnect error: no handler for ZMQ message sent from Redis CSV uploader.');
       }
  </code></pre>
  
  <p>I believe this is a legit/serious problem because a lot of programs just need to publish messages and then die, but how can we effectively ensure all messages get sent (though not necessarily received)?</p>
  
  <p>EDIT:
  One (potential) way to fix this is to do:</p>
  
  <pre><code>socket.send('xyz');
  socket.close(); // supposedly this will block until the above message is sent
  process.exit(0);
  </code></pre>