What is to-readable-stream?
The 'to-readable-stream' npm package is a simple utility that allows you to convert a string or buffer into a readable stream. This can be particularly useful when you need to work with stream-based APIs but only have static data to start with.
What are to-readable-stream's main functionalities?
Convert string to stream
This feature allows you to convert a simple string into a readable stream, which can then be used with any API that accepts streams. The example demonstrates creating a stream from a string and reading from it.
const toReadableStream = require('to-readable-stream');
const stream = toReadableStream('Hello, world!');
stream.on('data', (chunk) => {
console.log(chunk.toString()); // Outputs: Hello, world!
});
Convert buffer to stream
This feature enables the conversion of a buffer into a readable stream. Similar to the string example, this allows buffers to be used wherever streams are required. The code sample shows how to convert a buffer to a stream and read its contents.
const toReadableStream = require('to-readable-stream');
const buffer = Buffer.from('Hello, buffer!');
const stream = toReadableStream(buffer);
stream.on('data', (chunk) => {
console.log(chunk.toString()); // Outputs: Hello, buffer!
});
Other packages similar to to-readable-stream
into-stream
The 'into-stream' package offers similar functionality to 'to-readable-stream' by converting strings, buffers, or arrays into readable streams. It provides a bit more flexibility compared to 'to-readable-stream' by supporting arrays of items, which can be particularly useful when you need to stream multiple items in sequence.
streamifier
Streamifier is another package that can convert a buffer or a string to a stream. It is quite similar to 'to-readable-stream' but also supports creating streams from large objects, which might be useful for applications dealing with large datasets or files.
to-readable-stream
Convert a string/Buffer/Uint8Array to a readable stream
If you target Node.js 12 or later, you can use stream.Readable#from()
instead.
Install
$ npm install to-readable-stream
Usage
import toReadableStream from 'to-readable-stream';
toReadableStream('🦄🌈').pipe(process.stdout);
API
toReadableStream(value)
Returns a stream.Readable
.
value
Type: string | Buffer | Uint8Array
Value to convert to a stream.
Related