UNPKG

5.54 kBMarkdownView Raw
1# through2
2
3[![NPM](https://nodei.co/npm/through2.png?downloads&downloadRank)](https://nodei.co/npm/through2/)
4
5**A tiny wrapper around Node streams.Transform (Streams2) to avoid explicit subclassing noise**
6
7Inspired by [Dominic Tarr](https://github.com/dominictarr)'s [through](https://github.com/dominictarr/through) in that it's so much easier to make a stream out of a function than it is to set up the prototype chain properly: `through(function (chunk) { ... })`.
8
9Note: A **Streams3** version of through2 is available in npm with the tag `"1.0"` rather than `"latest"` so an `npm install through2` will get you the current Streams2 version (version number is 0.x.x). To use a Streams3 version use `npm install through2@1` to fetch the latest version 1.x.x. More information about Streams2 vs Streams3 and recommendations see the article **[Why I don't use Node's core 'stream' module](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html)**.
10
11```js
12fs.createReadStream('ex.txt')
13 .pipe(through2(function (chunk, enc, callback) {
14 for (var i = 0; i < chunk.length; i++)
15 if (chunk[i] == 97)
16 chunk[i] = 122 // swap 'a' for 'z'
17
18 this.push(chunk)
19
20 callback()
21 }))
22 .pipe(fs.createWriteStream('out.txt'))
23```
24
25Or object streams:
26
27```js
28var all = []
29
30fs.createReadStream('data.csv')
31 .pipe(csv2())
32 .pipe(through2.obj(function (chunk, enc, callback) {
33 var data = {
34 name : chunk[0]
35 , address : chunk[3]
36 , phone : chunk[10]
37 }
38 this.push(data)
39
40 callback()
41 }))
42 .on('data', function (data) {
43 all.push(data)
44 })
45 .on('end', function () {
46 doSomethingSpecial(all)
47 })
48```
49
50Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`.
51
52## API
53
54<b><code>through2([ options, ] [ transformFunction ] [, flushFunction ])</code></b>
55
56Consult the **[stream.Transform](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_transform)** documentation for the exact rules of the `transformFunction` (i.e. `this._transform`) and the optional `flushFunction` (i.e. `this._flush`).
57
58### options
59
60The options argument is optional and is passed straight through to `stream.Transform`. So you can use `objectMode:true` if you are processing non-binary streams (or just use `through2.obj()`).
61
62The `options` argument is first, unlike standard convention, because if I'm passing in an anonymous function then I'd prefer for the options argument to not get lost at the end of the call:
63
64```js
65fs.createReadStream('/tmp/important.dat')
66 .pipe(through2({ objectMode: true, allowHalfOpen: false },
67 function (chunk, enc, cb) {
68 cb(null, 'wut?') // note we can use the second argument on the callback
69 // to provide data as an alternative to this.push('wut?')
70 }
71 )
72 .pipe(fs.createWriteStream('/tmp/wut.txt'))
73```
74
75### transformFunction
76
77The `transformFunction` must have the following signature: `function (chunk, encoding, callback) {}`. A minimal implementation should call the `callback` function to indicate that the transformation is done, even if that transformation means discarding the chunk.
78
79To queue a new chunk, call `this.push(chunk)`&mdash;this can be called as many times as required before the `callback()` if you have multiple pieces to send on.
80
81Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error.
82
83If you **do not provide a `transformFunction`** then you will get a simple pass-through stream.
84
85### flushFunction
86
87The optional `flushFunction` is provided as the last argument (2nd or 3rd, depending on whether you've supplied options) is called just prior to the stream ending. Can be used to finish up any processing that may be in progress.
88
89```js
90fs.createReadStream('/tmp/important.dat')
91 .pipe(through2(
92 function (chunk, enc, cb) { cb(null, chunk) }, // transform is a noop
93 function (cb) { // flush function
94 this.push('tacking on an extra buffer to the end');
95 cb();
96 }
97 ))
98 .pipe(fs.createWriteStream('/tmp/wut.txt'));
99```
100
101<b><code>through2.ctor([ options, ] transformFunction[, flushFunction ])</code></b>
102
103Instead of returning a `stream.Transform` instance, `through2.ctor()` returns a **constructor** for a custom Transform. This is useful when you want to use the same transform logic in multiple instances.
104
105```js
106var FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) {
107 if (record.temp != null && record.unit = "F") {
108 record.temp = ( ( record.temp - 32 ) * 5 ) / 9
109 record.unit = "C"
110 }
111 this.push(record)
112 callback()
113})
114
115// Create instances of FToC like so:
116var converter = new FToC()
117// Or:
118var converter = FToC()
119// Or specify/override options when you instantiate, if you prefer:
120var converter = FToC({objectMode: true})
121```
122
123## See Also
124
125 - [through2-map](https://github.com/brycebaril/through2-map) - Array.prototype.map analog for streams.
126 - [through2-filter](https://github.com/brycebaril/through2-filter) - Array.prototype.filter analog for streams.
127 - [through2-reduce](https://github.com/brycebaril/through2-reduce) - Array.prototype.reduce analog for streams.
128 - [through2-spy](https://github.com/brycebaril/through2-spy) - Wrapper for simple stream.PassThrough spies.
129
130## License
131
132**through2** is Copyright (c) 2013 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.