Projekt

Obecné

Profil

Stáhnout (5.5 KB) Statistiky
| Větev: | Revize:
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/3) 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', () => doSomethingSpecial())
24
```
25

    
26
Or object streams:
27

    
28
```js
29
var all = []
30

    
31
fs.createReadStream('data.csv')
32
  .pipe(csv2())
33
  .pipe(through2.obj(function (chunk, enc, callback) {
34
    var data = {
35
        name    : chunk[0]
36
      , address : chunk[3]
37
      , phone   : chunk[10]
38
    }
39
    this.push(data)
40

    
41
    callback()
42
  }))
43
  .on('data', (data) => {
44
    all.push(data)
45
  })
46
  .on('end', () => {
47
    doSomethingSpecial(all)
48
  })
49
```
50

    
51
Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`.
52

    
53
## API
54

    
55
<b><code>through2([ options, ] [ transformFunction ] [, flushFunction ])</code></b>
56

    
57
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`).
58

    
59
### options
60

    
61
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()`).
62

    
63
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:
64

    
65
```js
66
fs.createReadStream('/tmp/important.dat')
67
  .pipe(through2({ objectMode: true, allowHalfOpen: false },
68
    (chunk, enc, cb) => {
69
      cb(null, 'wut?') // note we can use the second argument on the callback
70
                       // to provide data as an alternative to this.push('wut?')
71
    }
72
  )
73
  .pipe(fs.createWriteStream('/tmp/wut.txt'))
74
```
75

    
76
### transformFunction
77

    
78
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.
79

    
80
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.
81

    
82
Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error.
83

    
84
If you **do not provide a `transformFunction`** then you will get a simple pass-through stream.
85

    
86
### flushFunction
87

    
88
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.
89

    
90
```js
91
fs.createReadStream('/tmp/important.dat')
92
  .pipe(through2(
93
    (chunk, enc, cb) => cb(null, chunk), // transform is a noop
94
    function (cb) { // flush function
95
      this.push('tacking on an extra buffer to the end');
96
      cb();
97
    }
98
  ))
99
  .pipe(fs.createWriteStream('/tmp/wut.txt'));
100
```
101

    
102
<b><code>through2.ctor([ options, ] transformFunction[, flushFunction ])</code></b>
103

    
104
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.
105

    
106
```js
107
var FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) {
108
  if (record.temp != null && record.unit == "F") {
109
    record.temp = ( ( record.temp - 32 ) * 5 ) / 9
110
    record.unit = "C"
111
  }
112
  this.push(record)
113
  callback()
114
})
115

    
116
// Create instances of FToC like so:
117
var converter = new FToC()
118
// Or:
119
var converter = FToC()
120
// Or specify/override options when you instantiate, if you prefer:
121
var converter = FToC({objectMode: true})
122
```
123

    
124
## See Also
125

    
126
  - [through2-map](https://github.com/brycebaril/through2-map) - Array.prototype.map analog for streams.
127
  - [through2-filter](https://github.com/brycebaril/through2-filter) - Array.prototype.filter analog for streams.
128
  - [through2-reduce](https://github.com/brycebaril/through2-reduce) - Array.prototype.reduce analog for streams.
129
  - [through2-spy](https://github.com/brycebaril/through2-spy) - Wrapper for simple stream.PassThrough spies.
130
  - the [mississippi stream utility collection](https://github.com/maxogden/mississippi) includes `through2` as well as many more useful stream modules similar to this one
131

    
132
## License
133

    
134
**through2** is Copyright (c) Rod Vagg [@rvagg](https://twitter.com/rvagg) and additional contributors 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.
(2-2/4)