如何故意让我的 node.js 服务器崩溃? (我想在发生某些 fatal error 时这样做,以便立即引起我的注意并加以修复)
我看过这个帖子here但我不想使用 C 模块或运行无限循环(因为我的应用程序运行在我为使用的 CPU 时间量付费的服务器上)这意味着它会非常昂贵且难以最大化 CPU .
我尝试过使用 process.exit 和 process.abort,但这只会关闭调用它的模块。
例如,我的服务器是通过调用 node main.js 启动的,它需要我在其他文件中编写的几个自定义模块。如果在其他文件之一中调用了 process.exit 或 process.abort,那么它会正确关闭其他文件中发生的任何事情,但不会关闭整个 Node 服务器和 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 running indefinitely。
如果我删除 while true 循环,它只会打印出“发生错误,服务器现在将崩溃。”然后退出(因为没有更多的代码可以运行)。这证明 process.exit 命令正在运行,但 while (true) 循环仍在运行。
还有其他方法可以实现吗?
最佳答案
Javascript 中的无限循环简直是邪恶的,因为它们不允许事件循环执行任何正常的关闭处理,其中一些是必需的,以便允许将某些 Javascript 事件作为关闭的一部分进行处理过程。
如果你替换这个无限循环:
while (true){
console.log("Server still running");
}
用这个:
setInterval(function() {
console.log("server still running");
}, 1000);
然后您的服务器应该关闭。
关于javascript - 我怎样才能故意让我的 node.js 服务器崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36650667/