如何找出阻止 Node.js 退出的原因?

How to figure out what's holding Node.js from exiting?

我编写的各种 Node.js 脚本经常遇到这个问题。一切完成后,他们不会退出。一般是未关闭的socket或者readline接口。

等剧本大了,这个还真不好找。是否有某种工具可以告诉我 NodeJS 在等待什么?我正在寻求一个通用的解决方案,它可以帮助调试所有 NodeJS 在应该退出时不退出的情况。

样本:

图表 I. - 即使在侦听器被删除后,进程标准输入也会阻塞节点

const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
if (typeof process.stdin.setRawMode == "function")
    process.stdin.setRawMode(true);


const keypressListener = (stream, key) => {
    console.log(key);
    process.stdin.removeListener("keypress", keypressListener);
}
process.stdout.write("Press any key...");
process.stdin.on("keypress", keypressListener);

附件二。 - readline 如果忘记关闭界面会阻塞 Node

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

附件三。 - 忘记 setInterval 也会阻塞节点,祝你找到它

setInterval(() => { }, 2000);

why-is-node-running行吗?似乎完全符合您的需要。