尝试使用节点生成进程并读取其输出 我希望输出在一个文件中,并能够读取它。
这是我到目前为止的代码,但它会抛出错误 -
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
我做错了什么,我该怎么做才能做到这一点?
答案 0 :(得分:0)
您正在将子进程的输出连接到文件系统文件'out.log'
,因此它会到达那里,因此也不能通过stdout直接使用。您需要使用fs
核心模块通过文件系统路径直接读取输出文件。 var outBuffer = fs.readSync('out.log');