2013-10-25 57 views
1

我重定向detachedchild_process到文件的標準錯誤流之後,使用Node.js的分離一個催生孩子spawing

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

,並把該FD作爲spawn標準錯誤。

我正在尋找一種方法來截取寫入文件的數據。這意味着,當該子進程寫入某個內容時,我想在寫入該文件之前先對其進行處理。

我試着製作一個可寫的流,並給它而不是文件描述符來產生。但這並沒有幫助。

任何人都可以建議我該怎麼做到這一點?

另外,我是否可以正常產卵child_process(detached = false)並在data上收聽child.stdout事件,並且當我準備好時,我可以分開孩子。基本上,我想從child_process獲得一些初始數據,然後讓它作爲後臺進程運行並終止父進程。

回答

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) 

注的方式,我們管流:標準錯誤是可以讀取數據流,該processErrors是變換流是複式,f是一個可寫只有流。 processErrors流會處理數據並按照接收到的數據輸出(因此看起來像內部具有業務內部邏輯的PassThrough流)。

+0

這允許在寫入文件之前攔截數據。但是,我想從孩子那裏得到一些成功確認後,讓孩子分開。 –

+0

我不能分開孩子,直到它使用父母'stdout'和'stderr'。基本上,我不想設置'stdio:['ignore',out,err]'而讓孩子變成這樣我可以'child.unref()'和父進程可以退出。 –

+0

在這種情況下,這是非常棘手的,因爲你甚至不能刪除processErros流(從它刪除stderr並將其重新輸入到f),因爲f仍然由Node管理,所以你將無法將它分開... –