利用子进程实现NodeJS程序退出后自动重启

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

var child_process = require('child_process');

function start(nodefile) {
if (typeof start !== 'string') {
console.log('Has none file. like this: start("app.js")');
}

console.log('Master process is running.');

var proc = child_process.spawn('node', [nodefile]);

proc.stdout.on('data', function (data) {
console.log(data.toString());
});

proc.stderr.on('data', function (data) {
console.log(data.toString());
});

// 监测退出事件,删除原进程并重启新进程
proc.on('exit', function (code) {
console.log('child process exited with code ' + code);
delete(proc);
setTimeout(start, 5000);
});
}

module.exports = start;