【问题标题】:How to Start another process after process.exit in node如何在节点中的 process.exit 之后启动另一个进程
【发布时间】:2021-06-23 11:11:03
【问题描述】:
我想在另一个进程退出后运行一个进程。
例如,如果我正在运行一个节点 JS 文件并且我点击 CTRL + C,它应该关闭当前文件并从另一个 JS 文件运行另一个进程
类似的东西(伪代码):
process.on('exit', () => {
console.log("exiting")
}).then( //I am conscious it's wrong to put like that
//open another js file and run this process
);
【问题讨论】:
标签:
javascript
node.js
process
【解决方案1】:
不,这是不可能的,因为process 是一个代表当前 Node.js 进程的全局对象(阅读更多关于它的信息in the official docs)。当那个进程退出时,你的脚本就结束了,所以在那之后就不可能做任何事情了。
但是,您可以从调用 Node.js 脚本的地方运行某些内容,因为在您的脚本退出后调用者可能仍在运行。这可能是一个 bash 脚本、另一个 Node.js 进程或其他东西。
或者,您可以在process.on('exit', () => {...}) 的回调中生成一个新的独立进程,如下面的 sn-p 所示(阅读更多关于 in the official docs 的信息):
const spawn = require('child_process').spawn;
process.on('exit', () => {
const child = spawn('node', ['some_other_script.js'], {
detached: true,
stdio: 'ignore'
});
child.unref();
});
严格来说,这不是“在”进程退出之后——而是在父进程退出之前。不过,我认为这对您的示例没有任何影响。