データがストリームに書き込まれる順序は、読み取られる順序と同じであることが保証されています。ストリームに書き込む場合、データは書き込まれるかキューに入れられ、順序は変わりません。これは Node.js ソースからのものです。
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
state.needDrain = !ret;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
これは、データ イベントが発生する方法でもあります。
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
}
キューに入れられたデータがない限り、データ イベントはチャンクに対して発生しません。つまり、渡された順序でデータを取得します。