How to wrap a buffer as a stream2 Readable stream?

2019-01-08 10:26发布

问题:

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

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

回答1:

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



回答2:

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.

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)


回答3:

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

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.