How to wrap a buffer as a stream2 Readable stream with Node.js?

Sometimes, we want to wrap a buffer as a stream2 Readable stream with Node.js.

In this article, we’ll look at how to wrap a buffer as a stream2 Readable stream with Node.js.

How to wrap a buffer as a stream2 Readable stream with Node.js?

To wrap a buffer as a stream2 Readable stream with Node.js, we can use the stream.PassThrough method.

For instance, we write

const stream = require('stream');

const bufferStream = new stream.PassThrough();
bufferStream.end(Buffer.from('Test data.'));
bufferStream.pipe(process.stdout)

to call stream.PassThrough to create a new pass through stream instance.

Then we call end with a buffer to write the buffer into the stream.

And then we call pipe to pipe the stream into stdout.

Conclusion

To wrap a buffer as a stream2 Readable stream with Node.js, we can use the stream.PassThrough method.