Initial commit
[yaffs-website] / node_modules / through2 / README.md
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
7 Inspired 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
9 Note: As 2.x.x this module starts using **Streams3** instead of Stream2. To continue using a Streams2 version use `npm install through2@0` to fetch the latest version of 0.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
12 fs.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   .on('finish', function () {
24     doSomethingSpecial()
25   })
26 ```
27
28 Or object streams:
29
30 ```js
31 var all = []
32
33 fs.createReadStream('data.csv')
34   .pipe(csv2())
35   .pipe(through2.obj(function (chunk, enc, callback) {
36     var data = {
37         name    : chunk[0]
38       , address : chunk[3]
39       , phone   : chunk[10]
40     }
41     this.push(data)
42
43     callback()
44   }))
45   .on('data', function (data) {
46     all.push(data)
47   })
48   .on('end', function () {
49     doSomethingSpecial(all)
50   })
51 ```
52
53 Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`.
54
55 ## API
56
57 <b><code>through2([ options, ] [ transformFunction ] [, flushFunction ])</code></b>
58
59 Consult 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`).
60
61 ### options
62
63 The 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()`).
64
65 The `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:
66
67 ```js
68 fs.createReadStream('/tmp/important.dat')
69   .pipe(through2({ objectMode: true, allowHalfOpen: false },
70     function (chunk, enc, cb) {
71       cb(null, 'wut?') // note we can use the second argument on the callback
72                        // to provide data as an alternative to this.push('wut?')
73     }
74   )
75   .pipe(fs.createWriteStream('/tmp/wut.txt'))
76 ```
77
78 ### transformFunction
79
80 The `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.
81
82 To 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.
83
84 Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error.
85
86 If you **do not provide a `transformFunction`** then you will get a simple pass-through stream.
87
88 ### flushFunction
89
90 The 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.
91
92 ```js
93 fs.createReadStream('/tmp/important.dat')
94   .pipe(through2(
95     function (chunk, enc, cb) { cb(null, chunk) }, // transform is a noop
96     function (cb) { // flush function
97       this.push('tacking on an extra buffer to the end');
98       cb();
99     }
100   ))
101   .pipe(fs.createWriteStream('/tmp/wut.txt'));
102 ```
103
104 <b><code>through2.ctor([ options, ] transformFunction[, flushFunction ])</code></b>
105
106 Instead 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.
107
108 ```js
109 var FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) {
110   if (record.temp != null && record.unit == "F") {
111     record.temp = ( ( record.temp - 32 ) * 5 ) / 9
112     record.unit = "C"
113   }
114   this.push(record)
115   callback()
116 })
117
118 // Create instances of FToC like so:
119 var converter = new FToC()
120 // Or:
121 var converter = FToC()
122 // Or specify/override options when you instantiate, if you prefer:
123 var converter = FToC({objectMode: true})
124 ```
125
126 ## See Also
127
128   - [through2-map](https://github.com/brycebaril/through2-map) - Array.prototype.map analog for streams.
129   - [through2-filter](https://github.com/brycebaril/through2-filter) - Array.prototype.filter analog for streams.
130   - [through2-reduce](https://github.com/brycebaril/through2-reduce) - Array.prototype.reduce analog for streams.
131   - [through2-spy](https://github.com/brycebaril/through2-spy) - Wrapper for simple stream.PassThrough spies.
132   - the [mississippi stream utility collection](https://github.com/maxogden/mississippi) includes `through2` as well as many more useful stream modules similar to this one
133
134 ## License
135
136 **through2** is Copyright (c) 2013 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.