将child_process的标准输出和错误输出重定向到/dev/null或类似的地方

5
我正在使用Node.js创建一些child_processes (require('child_process')),我希望确保每个child_process的stdout/stderr不会传递到终端,因为我只想记录父进程的输出。是否有一种方法将child_processes中的stdout/stderr流重定向到/dev/null或其他不是终端的地方? https://nodejs.org/api/child_process.html 也许可以这样做:
var n = cp.fork('child.js',[],{
   stdio: ['ignore','ignore','ignore']
});

我刚刚尝试了一下,但好像没有起作用。

现在我试了这个:

var stdout, stderr;

if (os.platform() === 'win32') {
    stdout = fs.openSync('NUL', 'a');
    stderr = fs.openSync('NUL', 'a');
}
else {
    stdout = fs.openSync('/dev/null', 'a');
    stderr = fs.openSync('/dev/null', 'a');
}

然后是这个选项:

stdio: ['ignore',  stdout, stderr],

但那样做并没有解决问题,不过使用“detached:true”选项似乎可以使其工作。


1
你可以在你的分支进程中劫持 process.stdout.write,这个怎么样? - Yerken
很遗憾,我不能覆盖它,必须使用child_process来完成这个任务! - Alexander Mills
我想我实际上可以覆盖它,但通过child_process调用执行此操作有优势。 - Alexander Mills
1
在文档中看起来 stdio 选项是针对 spawn 而不是 fork,也许你想要使用 silent 选项? - mzulch
@mzulch 我认为“silent”选项可能是正确的。 - Alexander Mills
FYI https://dev59.com/uIHba4cB1Zd3GeqPMhQi - TheCodeArtist
1个回答

8

解决方案:

为了丢弃分叉子进程的 stdoutstderr

  1. 设置一个管道,即在分叉时使用 silent = True

  2. 将父进程的 stdoutstderr 管道重定向到 /dev/null


解释:

Node.js 文档指出:

为了方便起见,options.stdio 可以是以下字符串之一:

'pipe' - equivalent to ['pipe', 'pipe', 'pipe'] (the default)
'ignore' - equivalent to ['ignore', 'ignore', 'ignore']
'inherit' - equivalent to [process.stdin, process.stdout, process.stderr] or [0,1,2]

显然,childprocess.fork()不支持ignore;只有childprocess.spawn()支持。

fork支持一个silent选项,允许选择pipeinherit之间的差异。

在派生子进程时:
如果silent = True,则stdio = pipe
如果silent = False,则stdio = inherit

silent
Boolean

如果为true,则子进程的stdin、stdout和stderr将被管道传输到父进程,否则它们将从父进程继承。有关更多详细信息,请参见child_process.spawn()的stdio中的“pipe”和“inherit”选项。


谢谢,这个答案不错,我之前已经点赞了......目前我在想是否有一种方法可以直接将child_process的stderr/stdout管道传输到文件中,而不是先返回给父进程再写入文件。你有什么想法吗? - Alexander Mills
我猜在 child_process 中只需调用 process.stderr.pipe() 即可。 - Alexander Mills

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接