2017-02-20 14 views
2

私はNode.jsのストリームAPIでストリームを変換するには、彼らが到着したときにチャンクを変換するために、非同期機能を使用することで参照してください。 https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callbackNode.jsストリーム変換はチャンクの順序を維持しますか?

は、変換ストリームをいは、彼らが到着したのと同じ順序でチャンクを送信しますか?非同期関数では、明示的にそうではないためです。

答えて

3

短い答えは:はい、トランスフォームストリームはチャンクが同じ順序で送信されることを保証します。 (ここでは

)ストリームは、暗号化のため-sensative操作(またはビュン・解凍ファイルに使用される可能性がありますのではあなたが確認するために実行することができると切り取られる:

const {Transform} = require('stream'); 
 
const _ = require('lodash'); 
 
const h = require('highland'); 
 

 
const myTransform = new Transform({ 
 
    transform(chunk, encoding, callback) { 
 
     //Callback fires in a random amount of time 1-500 ms 
 
     setTimeout(() => callback(null, chunk), _.random(1, 500)); 
 
    }, 
 
    //Using objectMode to pass-trough Numbers, not strings/buffers 
 
    objectMode: true 
 
}); 
 

 
//I'm using 'highland' here to create a read stream 
 
//The read stream emits numbers from 1 to 100 
 
h(_.range(1, 100)) 
 
    .pipe(myTransform) 
 
    //Simply logging them as they go out of transform stream 
 
    .on('data', chunk => console.log(chunk.toString())); 
 

 
//The output is: 
 
// 1 
 
// 2 
 
// 3 
 
// 4 ... 
 
//Although the callbacks fire in random order

関連する問題