node.js:程序意外退出或只是挂起 [英] node.js: program either exits unexpectedly or just hangs

查看:255
本文介绍了node.js:程序意外退出或只是挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js中编写了一个执行一些网络操作的模块.我编写了一个使用此模块的小脚本(下面的变量check).看起来像这样:

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");
});

现在这是有趣的事情.当此代码作为mocha测试的一部分执行时,测试将按预期方式退出.我看到打印了日志语句,并且该过程退出了.

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.

将代码作为独立的节点脚本执行时,将打印出log语句,但是过程只是挂起.

When the code is executed as a standalone node script, the log statement gets printed, but the process just hangs.

当我尝试调试它并使用--debug-brk启动程序并使用node-inspector时,它会退出得很早!我看到process.on 'exit'被调用了.当模块中的一些内部回调尚未调用时,它将退出.因此,上面的log语句也不会打印.

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?

推荐答案

当您将其作为脚本运行,并且在完成"时挂起,这意味着节点仍注册有等待事件的回调. Node不知道这些事件不会再触发.如果您知道该退出了,可以直接致电process.exit(),也可以显式关闭/取消绑定/断开所有连接(网络连接,数据库连接等).如果您正确关闭了所有内容,则节点应退出.

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.

模块 wtfnode (Nathan Arthur提到)或

The module wtfnode (mentioned by Nathan Arthur) or why-is-node-running can be really helpful tracking this down.

这篇关于node.js:程序意外退出或只是挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆