node.js: program either exits unexpectedly or just hangs
Asked Answered
A

2

10

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?

Asymmetry answered 7/4, 2013 at 0:33 Comment(0)
R
19

When 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.

Ricardo answered 7/4, 2013 at 2:28 Comment(5)
Is there someway to find out what is keeping node open?Asymmetry
If you have node-inspector and can attach to the process and set a break point in node's event loop code, maybe. I've never successfully tracked one of these down. It's either obvious things like opening a DB connection but never explicitly closing it, or I just do process.exit() and get on with my life.Ricardo
process._getActiveHandles() and process._getActiveRequests() see #17960952Parma
Very useful tip! Saved me!Customary
why-is-node-running seems to have multiple issues that prevent it from working on node 5 and/or with the request module. wtfnode is working for me.Dis
C
0

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.

Contredanse answered 29/9, 2020 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.