node.js: program either exits unexpectedly or just hangs

南楼画角 提交于 2019-12-23 08:01:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15857568/node-js-program-either-exits-unexpectedly-or-just-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!