How can I purposefully crash my node.js server?

时间:2016-04-15 15:03:08

标签: javascript node.js crash

How can I purposefully crash my node.js server? (I want to do this when certain fatal errors occur so they are brought to my attention immediately to be fixed)

I have seen this post here but I do not want to use a C module or run an endless loop (since my app is running on a server where I pay for the amount of CPU time I use) which means it will be very costly and difficult to max out the CPU.

I have tried using process.exit and process.abort but that only closes the module it is called from.

For example my server is started by calling node main.js and it requires several custom modules I have written in other files. If process.exit or process.abort is called in one of those other files then it will close anything happening in those other files correctly but it will not close the entire node server and main.js.

Here is a simplified example of what is happening in code:

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

If I run

node main.js

then it will print out server still running indefinitely.

If I remove the while true loop it will simply print out "An error has occured and the server will now crash." and then exit (since there is no more code to run). This proves the process.exit command is being run and yet the while (true) loop still runs.

Any other ways I can accomplish this?

1 个答案:

答案 0 :(得分:2)

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

如果你替换这个无限循环:

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

用这个:

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

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