在节点中使用 fork 子进程时如何捕获错误?

koh*_*ohl 4 child-process node.js electron electron-packager

我正在使用 fork 方法在我的电子应用程序中生成一个子进程,我的代码如下所示

'use strict'
 const fixPath = require('fix-path');

 let func = () => {
   fixPath();   
   const child = childProcess.fork('node /src/script.js --someFlags', 
   {
     detached: true, 
     stdio: 'ignore',
   }

 });

 child.on('error', (err) => {
   console.log("\n\t\tERROR: spawn failed! (" + err + ")");
 });

 child.stderr.on('data', function(data) {
   console.log('stdout: ' +data);
 });

 child.on('exit', (code, signal) => {
   console.log(code);
   console.log(signal);
 });

 child.unref();
Run Code Online (Sandbox Code Playgroud)

但我的子进程立即退出,退出代码为 1 并发出信号,有没有办法可以捕获此错误?当我使用 childprocess.exec 方法时,我可以使用 stdout.on('error'... 是否有类似的 fork 方法?如果没有关于如何解决此问题的任何建议?

koh*_*ohl 7

设置选项“silent:true”,然后使用事件处理程序 stderr.on() 我们可以捕获错误(如果有)。请检查下面的示例代码:

 let func = () => {
   const child = childProcess.fork(path, args, 
   {
     silent: true,
     detached: true, 
     stdio: 'ignore',
   }

 });

 child.on('error', (err) => {
   console.log("\n\t\tERROR: spawn failed! (" + err + ")");
 });

 child.stderr.on('data', function(data) {
   console.log('stdout: ' +data);
 });

 child.on('exit', (code, signal) => {
   console.log(code);
   console.log(signal);
 });

 child.unref();
Run Code Online (Sandbox Code Playgroud)