PM2(Process Manager 2 )是具有内置负载均衡器的Node.js应用程序的生产运行时和进程管理器。 它允许您永久保持应用程序活跃,无需停机即可重新加载它们,并促进常见的Devops任务。
但PM2相对复杂,包比较大,我们其实可以用child_process,实现一个简单版的进程守护程序,在控制台时时看到并保存LOG,0依赖。
比如下面的代码自动执行 pro.bat,并记录程序错误日志,当异常退出后,会自动重启服务。
const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');
class Thread {
logDir = 'logs';
restartInterval = 4000;
__thread;
addLog(type, data) {
const date = (new Date()).toISOString();
const msg = date + ' ' + data.toString();
const logPath = path.join(this.logDir, date.substring(0, date.indexOf('T')) + '.' + type + '.log')
console.log(msg);
fs.appendFile(logPath, msg, () => { });
}
logMsg(data) { this.addLog('out', data) }
logErr(data) { this.addLog('err', data) }
init(cmd, args) {
this.logMsg(`Start ${cmd} ${args}`);
const thread = spawn(cmd, args);
thread.stdout.on('data', data => this.logMsg(data));
thread.stderr.on('data', data => this.logErr(data));
thread.on('close', (code) => {
this.logMsg(`Exited with code ${code}, will restart in ${this.restartInterval}`);
setTimeout(()=>{
this.init(cmd, args);
}, this.restartInterval);
});
this.__thread = thread;
}
stop() {
const __process = this.__thread;
if (__process) {
this.__thread = null;
__process.kill();
}
}
constructor(cmd, args) {
fs.mkdir(this.logDir, err => {});
this.init(cmd, args || []);
}
}
const thread = new Thread('deploy.bat');
回复 (0)
微信扫码 立即评论