我看到 Node.js Stream API 中的 Transform Streams 使用异步函数在块到达时对其进行转换: https ://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
Transform 流是否按照它们到达的顺序发送块?因为对于异步函数,情况并非如此。
我看到 Node.js Stream API 中的 Transform Streams 使用异步函数在块到达时对其进行转换: https ://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
Transform 流是否按照它们到达的顺序发送块?因为对于异步函数,情况并非如此。
简短的回答是:是的,转换流保证块以相同的顺序发送。(因为 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