UNPKG

5.51 kBMarkdownView Raw
1# through2
2
3<!--
4
5soon ...
6
7[![Build Status](https://secure.travis-ci.org/rvagg/through2.png)](http://travis-ci.org/rvagg/through2)
8
9[![Build Status](https://saucelabs.com/browser-matrix/through2-sauce.svg)](https://travis-ci.org/rvagg/through2)
10
11-->
12
13[![NPM](https://nodei.co/npm/through2.png?compact=true)](https://nodei.co/npm/through2/)
14
15<!--
16not happy with these, we need to peg to readable-stream@1.0.x so it'll always report out-of-date
17
18[![david-dm](https://david-dm.org/rvagg/through2.png)](https://david-dm.org/rvagg/through2/)
19[![david-dm](https://david-dm.org/rvagg/through2/dev-status.png)](https://david-dm.org/rvagg/through2#info=devDependencies/)
20-->
21
22**A tiny wrapper around Node streams.Transform (Streams2) to avoid explicit subclassing noise**
23
24Inspired 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) { ... })`.
25
26Note: 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 [here](http://www.nearform.com/nodecrunch/dont-use-nodes-core-stream-module).
27
28```js
29fs.createReadStream('ex.txt')
30 .pipe(through2(function (chunk, enc, callback) {
31
32 for (var i = 0; i < chunk.length; i++)
33 if (chunk[i] == 97)
34 chunk[i] = 122 // swap 'a' for 'z'
35
36 this.push(chunk)
37
38 callback()
39
40 }))
41 .pipe(fs.createWriteStream('out.txt'))
42```
43
44Or object streams:
45
46```js
47var all = []
48
49fs.createReadStream('data.csv')
50 .pipe(csv2())
51 .pipe(through2.obj(function (chunk, enc, callback) {
52
53 var data = {
54 name : chunk[0]
55 , address : chunk[3]
56 , phone : chunk[10]
57 }
58
59 this.push(data)
60
61 callback()
62
63 }))
64 .on('data', function (data) {
65 all.push(data)
66 })
67 .on('end', function () {
68 doSomethingSpecial(all)
69 })
70```
71
72Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`.
73
74## API
75
76<b><code>through2([ options, ] [ transformFunction ] [, flushFunction ])</code></b>
77
78Consult 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`).
79
80### options
81
82The 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()`).
83
84The `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:
85
86```js
87fs.createReadStream('/tmp/important.dat')
88 .pipe(through2({ objectMode: true, allowHalfOpen: false }, function (chunk, enc, cb) {
89
90 this.push(new Buffer('wut?'))
91 cb()
92
93 })
94 .pipe(fs.createWriteStream('/tmp/wut.txt'))
95```
96
97### transformFunction
98
99The `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.
100
101To 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.
102
103If you **do not provide a `transformFunction`** then you will get a simple simple pass-through stream.
104
105### flushFunction
106
107The 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.
108
109<b><code>through2.ctor([ options, ] transformFunction[, flushFunction ])</code></b>
110
111Instead 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.
112
113```js
114var FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) {
115 if (record.temp != null && record.unit = "F") {
116 record.temp = ( ( record.temp - 32 ) * 5 ) / 9
117 record.unit = "C"
118 }
119 this.push(record)
120 callback()
121})
122
123// Create instances of FToC like so:
124var converter = new FToC()
125// Or:
126var converter = FToC()
127// Or specify/override options when you instantiate, if you prefer:
128var converter = FToC({objectMode: true})
129```
130
131## See Also
132
133 - [through2-map](https://github.com/brycebaril/through2-map) - Array.prototype.map analog for streams.
134 - [through2-filter](https://github.com/brycebaril/through2-filter) - Array.prototype.filter analog for streams.
135 - [through2-reduce](https://github.com/brycebaril/through2-reduce) - Array.prototype.reduce analog for streams.
136 - [through2-spy](https://github.com/brycebaril/through2-spy) - Wrapper for simple stream.PassThrough spies.
137
138## License
139
140**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.