我看到Node.js Stream API中的Transform Streams使用异步函数在它们到达时转换块: https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
转换流是否以与它们到达时相同的顺序发送块?因为使用异步函数,这不是明确的情况。
答案 0 :(得分:3)
简短回答是:是的,转换流保证以相同的顺序发送块。 (因为Streams可能用于命令敏感操作(用于加密或压缩 - 解压缩文件)
这是一个剪辑,你可以运行以确保:
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