如何提高NodeJS程序的稳定性?

当我们写了个NodeJS程序的时候,一般用node yourjsfile.js命令启动该程序。但是如果程序中有东西出错,这个进程就会退出。我们写程序不可能保证万无一失,肯定有些没有处理的错误,这就 让很多人觉得NodeJS不稳定,容易产生很多故障。 下面我就讲讲几种方法增加你的NodeJS程序的稳定性。

1.使用 try{…} catch(error){…} 来执行容易出错的代码段。比如解析一个外来的json字符串等。

2.使用 process.on(‘uncaughtException’, function(err){…}); 来处理未被捕捉的错误。

3.试用奶妈进程来启动你的程序,检测子进程的退出,然后自动重启该进程。比如 mother.js :

start();
function start()
{
console.log('Mother process is running.');
var ls = require('child_process').spawn('node', ['yourjsfile.js']);
ls.stdout.on('data', function (data)
{
console.log(data.toString());
});
ls.stderr.on('data', function (data)
{
console.log(data.toString());
});
ls.on('exit', function (code)
{
console.log('child process exited with code ' + code);
delete(ls);
setTimeout(start,5000);
});
}

4.使用 nohup 让nodejs进程在后台运行。 比如运行”nohup node yourjsfile.js > /dev/null &”