Node.js在产卵后分离一个衍生的孩子

时间:2013-10-25 09:14:54

标签: node.js spawn child-process

我正在使用

detached child_process的stderr流重定向到文件
fd = fs.openSync('./err.log', 'a');

并将此fd作为stderr传递到spawn

我正在寻找一种拦截写入文件的数据的方法。这意味着,当该子进程写入某些内容时,我想在写入该文件之前对其进行处理。

我尝试制作一个可写流并将其赋予而不是文件描述符来生成。但这没有帮助。

任何人都可以建议我如何实现这一目标?

另外,我可以正常生成child_process(detached = false)并监听data child.stdout事件,当我准备好时,我可以分离孩子。基本上,我想从child_process获得一些初始数据,然后让它作为后台进程运行并终止父进程。

1 个答案:

答案 0 :(得分:1)

你想要的是Transform stream

以下是您的问题的可能解决方案:

var child = spawn( /* whatever options */ )
var errFile = fs.createWriteStream('err.log', { flags: 'w' })
var processErrors = new stream.Transform()
processErrors._transform = function (data, encoding, done) {
  // Do what you want with the data here.
  // data is most likely a Buffer object
  // When you're done, send the data to the output of the stream:
  this.push(data)
  done() // we're done processing this chunk of data
}
processErrors._flush = function(done) {
  // called at the end, when no more data will be provided
  done()
}

child.stderr.pipe(processErrors).pipe(f)

注意我们管道流的方式:stderr是一个可读流,processErrors是一个Duplex转换流,f只是一个可写流。 processErrors流将处理数据并在收到数据时将其输出(因此看起来像内部有业务内部逻辑的PassThrough流。)