Jun*_*ius 3 javascript asynchronous node.js node-streams
我看到 Node.js Stream API 中的转换流使用异步函数在块到达时对其进行转换: https ://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
转换流是否按照块到达的顺序发送块?因为对于异步函数,情况并非如此。
简短的回答是:是的,转换流保证块以相同的顺序发送。(因为 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 orderRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1341 次 |
| 最近记录: |