我怎样才能故意让我的 node.js 服务器崩溃?

How can I purposefully crash my node.js server?

如何故意使我的 node.js 服务器崩溃? (我想在发生某些致命错误时这样做,以便立即引起我的注意并加以修复)

我看过这个 post here 但我不想使用 C 模块或 运行 无限循环(因为我的应用程序正在 运行ning我为我使用的 CPU 时间付费的服务器)这意味着将非常昂贵且难以最大化 CPU.

我尝试过使用 process.exit 和 process.abort,但这只会关闭调用它的模块。

例如,我的服务器是通过调用节点 main.js 启动的,它需要我在其他文件中编写的几个自定义模块。如果在其他文件之一中调用了 process.exit 或 process.abort ,那么它将正确关闭那些其他文件中发生的任何事情,但不会关闭整个节点服务器和 main.js.

这是代码中发生的事情的简化示例:

//crashServer.js
var exampleVar;

module.exports = function(){
    if (!exampleVar){
        var err = new Error("An error has occured");
        Error.captureStackTrace(err);
        //error logging code
        console.log("An error has occured and the server will now crash.");
        process.exit();
    }
};

//main.js
var crashServer = require("./crashServer.js");

crashServer();
while (true){
    console.log("Server still running");
}

如果我运行

node main.js

然后它将无限期地打印出 server still 运行ning。

如果我删除 while true 循环,它将简单地打印出 "An error has occured and the server will now crash." 然后退出(因为没有更多代码到 运行)。这证明 process.exit 命令正在 运行 而 while (true) 循环仍然是 运行s.

还有其他方法可以实现吗?

Javascript 中的无限循环简直是邪恶的,因为它们不允许事件循环执行任何正常的关闭处理,其中一些是为了允许某些 Javascript 事件作为关闭过程的一部分进行处理。

如果替换这个无限循环:

while (true){
    console.log("Server still running");
}

有了这个:

setInterval(function() {
    console.log("server still running");
}, 1000);

然后您的服务器应该关闭。