Node.js在spawing之后分离一个产生的小孩
我正在使用一个detached
child_process
的stderrstreamredirect到一个文件
fd = fs.openSync('./err.log', 'a');
并将这个fd作为stderr传入spawn
。
我正在寻找一种方法来截取写入文件的数据。 这意味着,当那个subprocess写什么的时候,我想在写入这个文件之前先处理它。
我试着做一个可写的stream,并给它,而不是文件描述符产卵。 但是这并没有帮助。
任何人都可以build议我怎么能做到这一点?
另外,我可以正常产生一个child_process( detached = false
),并监听child.stdout
data
事件,当我准备好时,我可以分离孩子。 所以基本上,我想要一些来自child_process
初始数据,然后让它作为后台进程运行并终止父进程。
你想要的是一个转换stream 。
这是你的问题的一个可能的解决scheme:
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)
请注意我们pipe道stream的方式:stderr是一个可读stream,processErrors是一个Duplexstream,而f是一个Writablestream。 processErrorsstream会处理数据,并按照接收到的数据输出(因此看起来就像是一个PassThroughstream,其内部的业务逻辑)。