Node.js Stream Transform 是否保持块的顺序?

Does Node.js Stream Transform maintain the order of the chunks?

我看到 Node.js 流 API 中的转换流使用异步函数在块到达时对其进行转换: https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback

转换流发送块的顺序是否与它们到达时的顺序相同?因为对于异步函数,情况并非如此。

简短的回答是:是的,转换流保证块以相同的顺序发送。 (因为流可能用于 order-sensative 操作(用于加密或 zipping-unzipping 文件)

这是一个片段,您可以运行确保:

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