in node.js scripts have written, notice if last line synchronous call, doesn't complete before node.js exits.
i have never seen console.log
statement fail run/complete before exiting, have seen other statements fail complete before exiting, , believe synchronous. see why callback of async function fail fire of course in case.
the code in question zeromq .send()
call so:
var zmq = require('zmq'); var pub = zmq.socket('pub'); pub.bindsync('tcp://127.0.0.1:5555'); setinterval(function(){ pub.send('polyglot'); },500);
the above code works expected...but if remove setinterval()
, call this:
var zmq = require('zmq'); var pub = zmq.socket('pub'); pub.bindsync('tcp://127.0.0.1:5555'); pub.send('polyglot'); //this message not delivered before exit process.exit(0);
...then message not delivered - program apparently exit before pub.send()
call completes.
what best way ensure statement completes before exiting in node.js ? shutdown hooks work here, afraid masking problem since can't put need ensure runs in shutdown hook.
this problem can demonstrated way:
if (typeof messagehandler[nameofhandlerfunction] == 'function') { reply.send('success'); messagehandler[nameofhandlerfunction](null, args); } else { reply.send('failure'); //***this call might not complete before error thrown below.*** throw new error('smartconnect error: no handler zmq message sent redis csv uploader.'); }
i believe legit/serious problem because lot of programs need publish messages , die, how can ensure messages sent (though not received)?
edit: 1 (potential) way fix do:
socket.send('xyz'); socket.close(); // supposedly block until above message sent process.exit(0);
diving zeromq.node, can see socket.send
pushes data _outgoing
:
this._outgoing.push([msg, flags]);
... , calls _flush
iff zmq.zmq_sndmore unset:
this._flush();
looks _flush
doing socket write. if _flush()
fails, it emits error.
edit:
i'm guessing calling pub.unbind()
before exiting, force _flush()
called:
pub.unbind('tcp://127.0.0.1:5555', function(err) { if (err) console.log(err); process.exit(0); // not needed });