node.js 如何将缓冲区包装为 stream2 可读流?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16038705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:13:45  来源:igfitidea点击:

How to wrap a buffer as a stream2 Readable stream?

node.jsnode.js-stream

提问by Jerome WAGNER

How can I transform a node.js buffer into a Readable stream following using the stream2 interface ?

如何使用 stream2 接口将 node.js 缓冲区转换为可读流?

I already found this answerand the stream-buffers module but this module is based on the stream1 interface.

我已经找到了这个答案和流缓冲区模块,但这个模块基于 stream1 接口。

采纳答案by Gabriel Llamas

With streamifieryou can convert strings and buffers to readable streams with the new stream api.

使用streamifier,您可以使用新的流 api 将字符串和缓冲区转换为可读流。

回答by zjonsson

The easiest way is probably to create a new PassThrough stream instance, and simply push your data into it. When you pipe it to other streams, the data will be pulled out of the first stream.

最简单的方法可能是创建一个新的 PassThrough 流实例,然后简单地将数据推送到其中。当您通过管道将其传输到其他流时,数据将从第一个流中拉出。

var stream = require('stream');

// Initiate the source
var bufferStream = new stream.PassThrough();

// Write your buffer
bufferStream.end(new Buffer('Test data.'));

// Pipe it to something else  (i.e. stdout)
bufferStream.pipe(process.stdout)

回答by morris4

As natevw suggested, it's even more idiomatic to use a stream.PassThrough, and endit with the buffer:

正如 natevw 所建议的那样,使用 astream.PassThroughend它与缓冲区更加惯用:

var buffer = new Buffer( 'foo' );
var bufferStream = new stream.PassThrough();
bufferStream.end( buffer );
bufferStream.pipe( process.stdout );

This is also how buffers are converted/piped in vinyl-fs.

这也是缓冲区在vinyl-fs中转换/管道的方式。