What is stream-array?
The stream-array npm package allows you to create a readable stream from an array of data. This can be useful for processing data in a stream-based manner, which is often more efficient and scalable than processing data in a batch.
What are stream-array's main functionalities?
Create a readable stream from an array
This feature allows you to convert an array into a readable stream. The code sample demonstrates how to create a readable stream from an array of numbers and log each chunk of data as it is read from the stream.
const streamArray = require('stream-array');
const array = [1, 2, 3, 4, 5];
const readableStream = streamArray(array);
readableStream.on('data', (chunk) => {
console.log(chunk);
});
Pipe the stream to another writable stream
This feature allows you to pipe the readable stream created from an array to another writable stream. The code sample demonstrates how to create a readable stream from an array of strings and pipe it to a writable stream that logs each chunk of data.
const streamArray = require('stream-array');
const { Writable } = require('stream');
const array = ['a', 'b', 'c'];
const readableStream = streamArray(array);
const writableStream = new Writable({
write(chunk, encoding, callback) {
console.log(chunk.toString());
callback();
}
});
readableStream.pipe(writableStream);
Other packages similar to stream-array
from2
The from2 package provides a way to create a readable stream from a variety of sources, including arrays, buffers, and iterators. It offers more flexibility compared to stream-array, which is specifically designed for arrays.
readable-stream
The readable-stream package is a core Node.js module that provides a standard interface for working with streams. It is more comprehensive and versatile than stream-array, supporting a wide range of stream operations beyond just converting arrays to streams.
through2
The through2 package allows you to create transform streams, which can modify or transform the data as it passes through. While stream-array focuses on creating readable streams from arrays, through2 provides more advanced stream manipulation capabilities.
stream-array
Pipe an Array through Node.js streams. This is rather useful for testing other
streams.
Usage
var streamify = require('stream-array'),
os = require('os');
streamify(['1', '2', '3', os.EOL]).pipe(process.stdout);
API
streamify(Array)
The result of require is a 'function' that when invoked, will return a Readable Stream.
var streamify = require('stream-array');
The Array passed into stream-array() can contain any type, as it assumes the receiving stream can handle it. Each element will be dequeued and pushed into the following piped stream.
var readable = streamify(['Hello', new Buffer('World')]);
This Stream will emit each element of the source array as chunks.
readable(['1', '2', '3', os.EOL]).pipe(process.stdout);
123\n
Install
npm install stream-array
License
MIT License