簡體   English   中英

Node.js在生成后分離了一個生成的孩子

[英]Node.js detach a spawned child after spawing

我正在使用以下命令將一個detached child_process的stderr流重定向到一個文件

fd = fs.openSync('./err.log', 'a');

並將此fd作為stderr在spawn傳遞。

我正在尋找一種攔截寫入文件的數據的方法。 意思是,當那個子進程寫東西時,我想在寫入文件之前對其進行處理。

我嘗試制作可寫流,並提供它而不是生成文件描述符。 但這沒有幫助。

誰能建議我該如何實現?

另外,我是否可以正常生成child_process( detached = false )並偵聽child.stdout data事件,當我准備就緒時,可以分離孩子。 所以基本上,我想要child_process一些初始數據,然后讓它作為后台進程運行並終止父進程。

您需要的是Transform流

這是您的問題的可能解決方案:

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是雙工的Transform流,而f是僅可寫流。 processErrors流將處理數據並在收到數據后將其輸出(因此看起來像PassThrough流,內部具有您的業務內部邏輯)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM