I wrote a module in node.js that performs some network operation. I wrote a small script that uses this module (the variable check
below). It looks like this:
check(obj, function (err, results) {
// ...
console.log("Check completed");
});
Now here is the interesting thing. When this code executes as part of a mocha
test, the test exits as expected. I see the log statement printed and the process exits.
When the code is executed as a standalone node script, the log statement gets printed, but the process just hangs.
When I try to debug it and I start the program using --debug-brk
and use node-inspector
, it exits early! I see that process.on 'exit'
is called. It exits while some internal callbacks within the module weren't called yet. So the log statement above isn't printed either.
I am stuck now and am not sure why this is happening. Has anyone seen similar behaviour?
I wrote a module in node.js that performs some network operation. I wrote a small script that uses this module (the variable check
below). It looks like this:
check(obj, function (err, results) {
// ...
console.log("Check completed");
});
Now here is the interesting thing. When this code executes as part of a mocha
test, the test exits as expected. I see the log statement printed and the process exits.
When the code is executed as a standalone node script, the log statement gets printed, but the process just hangs.
When I try to debug it and I start the program using --debug-brk
and use node-inspector
, it exits early! I see that process.on 'exit'
is called. It exits while some internal callbacks within the module weren't called yet. So the log statement above isn't printed either.
I am stuck now and am not sure why this is happening. Has anyone seen similar behaviour?
Share Improve this question asked Apr 7, 2013 at 0:33 AishwarAishwar 9,71411 gold badges62 silver badges84 bronze badges2 Answers
Reset to default 19When you run it as a script and it hangs when "done", it means node still has callbacks registered waiting for events. Node doesn't know that those events won't fire anymore. You can either just call process.exit()
if you know it's time to exit, or you can explicitly close/unbind/disconnect everything (network connections, db connections, etc). If you properly close everything, node should then exit.
The module wtfnode (mentioned by Nathan Arthur) or why-is-node-running can be really helpful tracking this down.
If the program exits unexpectedly, it can be because the event loop becomes empty and there is nothing else to do (because some code forgot to emit an error or do something else to keep the event loop going). In this case Node exits with code 0 and you won't get any error messages whatsoever, so it can be really confusing.
See https://github.com/archiverjs/node-archiver/issues/457 for an example of this happening.