Node.js Stream Transform是否保持块的顺序? [英] Does Node.js Stream Transform maintain the order of the chunks?

查看:129
本文介绍了Node.js Stream Transform是否保持块的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到,Node.js Stream API中的Transform Streams使用异步函数在块到达时转换块:
https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback

I see in that the Transform Streams in the Node.js Stream API uses an asynchronous function to transform the chunks when they arrive: https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback

转换流是否发送他们到达时的顺序是多少?因为使用异步函数,这不是明确的情况。

Does the Transform stream sends the chunks at the same order as they arrive? Because with an asynchronous function, that is not explicitly the case.

推荐答案

简短回答是:是的,转换流保证以相同的顺序发送块。 (因为Streams可能用于顺序敏感操作(用于加密或压缩 - 解压缩文件)

Short answer is: yes, transform stream guaranties that chunks are sent in the same order. (Because Streams might be used for order-sensative operations (for cryptography, or zipping-unzipping files)

这是一个可以运行的剪切,以确保:

Here is a snipped that you could run to make sure:

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

这篇关于Node.js Stream Transform是否保持块的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆