1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
| var eos = require('end-of-stream')
| var shift = require('stream-shift')
|
| module.exports = each
|
| function each (stream, fn, cb) {
| var want = true
| var error = null
| var ended = false
| var running = false
| var calling = false
|
| stream.on('readable', onreadable)
| onreadable()
|
| if (cb) eos(stream, {readable: true, writable: false}, done)
| return stream
|
| function done (err) {
| if (!error) error = err
| ended = true
| if (!running) cb(error)
| }
|
| function onreadable () {
| if (want) read()
| }
|
| function afterRead (err) {
| running = false
|
| if (err) {
| error = err
| if (ended) return cb(error)
| stream.destroy(err)
| return
| }
| if (ended) return cb(error)
| if (!calling) read()
| }
|
| function read () {
| while (!running && !ended) {
| want = false
|
| var data = shift(stream)
| if (ended) return
| if (data === null) {
| want = true
| return
| }
|
| running = true
| calling = true
| fn(data, afterRead)
| calling = false
| }
| }
| }
|
|