当输出是文件时,如何从生成的子节点读取nodejs中的输出?

时间:2016-10-29 13:36:00

标签: node.js

尝试使用节点生成进程并读取其输出 我希望输出在一个文件中,并能够读取它。

这是我到目前为止的代码,但它会抛出错误 -

const outFile = fs.openSync('out.log', 'a')
const errFile = fs.openSync('err.log', 'a')
const child = childProcess.spawn('node', [pathToJsFile], {
  stdio: ['ignore', outFile, errFile],
  detached: true
})
child.unref()
console.log(child.stdio)
console.log('waiting for output')
child.stdio[1].on('data', (data)=> { // ==> get error since stdio[1] is null

如评论中所述,当我查看child.stdio时,我看到[null, null, null]
但是,当我查看文件时,我可以看到输出被写入 我正在使用节点4.2.1

我做错了什么,我该怎么做才能做到这一点?

1 个答案:

答案 0 :(得分:0)

您正在将子进程的输出连接到文件系统文件'out.log',因此它会到达那里,因此也不能通过stdout直接使用。您需要使用fs核心模块通过文件系统路径直接读取输出文件。 var outBuffer = fs.readSync('out.log');