through2
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
readable-stream | 3.6.2 | 32.46 kB | MIT | prod |
Through2 is a tiny, efficient Node.js library that wraps around the streams.Transform interface. This allows for an easy-to-use way to handle stream transforms without the complications and verbosity of subclassing. Inspired by Dominic Tarr's 'through' package, through2 offers an easier way to create a stream out of a function. Its main use is in systems and processes dealing with stream manipulation or transformation, such as reading files, transforming data, and feeding the transformed results into a writeable stream.
The use of through2 is straightforward and revolves around passing in a transform function. Here’s a code example of through2 being used to read from a file, manipulate the data, and then write to another file:
const through2 = require('through2');
const fs = require('fs');
fs.createReadStream('ex.txt')
.pipe(through2(function (chunk, enc, callback) {
for (let i = 0; i < chunk.length; i++)
if (chunk[i] == 97)
chunk[i] = 122 // swap 'a' for 'z'
this.push(chunk)
callback()
}))
.pipe(fs.createWriteStream('out.txt'))
.on('finish', () => console.log('Done!'));
The second code example shows an object stream:
const all = [];
fs.createReadStream('data.csv')
.pipe(csv2())
.pipe(through2.obj(function (chunk, enc, callback) {
const data = {
name : chunk[0],
address : chunk[3],
phone : chunk[10]
}
this.push(data)
callback()
}))
.on('data', (data) => {
all.push(data)
})
.on('end', () => {
console.log(all)
})
These examples show through2 working with both plain data and object streams.
The documentation for through2 is contained within its Readme file on Github, specifically at https://github.com/rvagg/through2. A detailed explanation of the API, including its methods and options, is provided. For a complete understanding of through2’s transform and flush functions, refer to the stream.Transform documentation on the Node.js official site at https://nodejs.org/api/stream.html#stream_class_stream_transform.