发生未捕获的异常时重启 Node.js 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19336435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restart Node.js application when uncaught exception occurs
提问by hexacyanide
How would I be able to restart my app when an exception occurs?
发生异常时如何重新启动我的应用程序?
process.on('uncaughtException', function(err) {
// restart app here
});
回答by hexacyanide
You could run the process as a fork of another process, so you can fork it if it dies. You would use the native Clustermodule for this:
您可以将该进程作为另一个进程的分叉来运行,因此如果它死了,您可以分叉它。您将为此使用本机Cluster模块:
var cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
});
}
if (cluster.isWorker) {
// put your code here
}
This code spawns one worker process, and if an error is thrown in the worker process, it will close, and the exit will respawn another worker process.
这段代码产生一个工作进程,如果在工作进程中抛出错误,它将关闭,退出将重新产生另一个工作进程。
回答by Sriharsha
You have a couple of options..
你有几个选择..
Restart the application using monitor like nodemon/forever
process.on('uncaughtException', function (err) {
console.log(err); //Send some notification about the error
process.exit(1); });start your application using
nodemon ./server.js
forever server.js start
Restart using the cluster
使用像 nodemon/forever 这样的监视器重新启动应用程序
process.on('uncaughtException', function (err) {
console.log(err); //发送一些关于错误的通知
process.exit(1); });使用
nodemon ./server.js
永远 server.js 开始
使用集群重启
This method involves a cluster of process, where the master process restarts any child process if they killed
这种方法涉及一个进程集群,如果它们被杀死,主进程会重新启动任何子进程
var cluster = require('cluster');
if (cluster.isMaster) {
var i = 0;
for (i; i< 4; i++){
cluster.fork();
}
//if the worker dies, restart it.
cluster.on('exit', function(worker){
console.log('Worker ' + worker.id + ' died..');
cluster.fork();
});
}
else{
var express = require('express');
var app = express();
.
.
app.use(app.router);
app.listen(8000);
process.on('uncaughtException', function(){
console.log(err);
//Send some notification about the error
process.exit(1);
}
}

