2017-03-22 38 views
0

它是變換流節點js的簡單示例。變換流節點中的回調函數js

代碼:

const { Transform } = require('stream'); 

const transtream = new Transform({ 
    transform(chunk, encoding, callback){ 
     this.push(chunk.toString().toUpperCase()); 
     callback() 
    } 
}); 

process.stdin.pipe(transtream).pipe(process.stdout); 

這工作得很好:

Input: hi this is me 
Output: HI THIS IS ME 
Input: hi this is me again 
Output: HI THIS IS ME AGAIN 

現在,如果我不調用回調函數,這個程序並不像以前那樣工作。

新代碼:

const { Transform } = require('stream'); 

const transtream = new Transform({ 
    transform(chunk, encoding, callback){ 
     this.push(chunk.toString().toUpperCase()); 
     //callback() 
    } 
}); 

process.stdin.pipe(transtream).pipe(process.stdout); 

現在,當我給輸入,它的工作原理是第一次,那麼它停止轉換數據。所以沒有輸出第二個輸入。

Input: hi this is me 
Output: HI THIS IS ME 
Input: hi this is me again 
Input: hey 

問題:爲什麼需要回調?爲什麼程序在未被調用時會改變行爲?

+0

你在問爲什麼需要回調? –

+0

你能澄清問題是什麼嗎? – richsilv

+0

回調函數在讀取數據流時將數據壓入嗎? –

回答

0

我只是複製粘貼through2 npm模塊的文檔的一部分。

通常,當你想在節點js中使用流播放時,最好使用npm模塊。

transformFunction必須具有以下簽名:function(chunk,encoding,callback){}。最小的實現應該調用回調函數來表明轉換已完成,即使該轉換意味着丟棄該塊。

若要排隊一個新塊,請調用this.push(塊) - 如果您有多個要發送的塊,可以根據需要多次調用此回調函數()之前的次數。

或者,您可以使用回調(err,chunk)作爲發出單個塊或錯誤的簡寫。