Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
core-util-is | 1.0.3 | 1.85 kB | MIT | prod | |
inherits | 2.0.4 | 1.98 kB | ISC | prod | |
isarray | 1.0.0 | 1.97 kB | MIT | prod | |
process-nextick-args | 2.0.1 | 1.62 kB | MIT | prod | |
readable-stream | 2.3.8 | 25.14 kB | MIT | prod | |
safe-buffer | 5.1.2 | 9.59 kB | MIT | prod | |
string_decoder | 1.1.1 | 4.72 kB | MIT | prod | |
through2 | 2.0.5 | 3.96 kB | MIT | prod | |
util-deprecate | 1.0.2 | 2.19 kB | MIT | prod | |
xtend | 4.0.2 | 2.47 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.