Initial commit
[yaffs-website] / node_modules / fstream / lib / collect.js
1 module.exports = collect
2
3 function collect (stream) {
4   if (stream._collected) return
5
6   if (stream._paused) return stream.on('resume', collect.bind(null, stream))
7
8   stream._collected = true
9   stream.pause()
10
11   stream.on('data', save)
12   stream.on('end', save)
13   var buf = []
14   function save (b) {
15     if (typeof b === 'string') b = new Buffer(b)
16     if (Buffer.isBuffer(b) && !b.length) return
17     buf.push(b)
18   }
19
20   stream.on('entry', saveEntry)
21   var entryBuffer = []
22   function saveEntry (e) {
23     collect(e)
24     entryBuffer.push(e)
25   }
26
27   stream.on('proxy', proxyPause)
28   function proxyPause (p) {
29     p.pause()
30   }
31
32   // replace the pipe method with a new version that will
33   // unlock the buffered stuff.  if you just call .pipe()
34   // without a destination, then it'll re-play the events.
35   stream.pipe = (function (orig) {
36     return function (dest) {
37       // console.error(' === open the pipes', dest && dest.path)
38
39       // let the entries flow through one at a time.
40       // Once they're all done, then we can resume completely.
41       var e = 0
42       ;(function unblockEntry () {
43         var entry = entryBuffer[e++]
44         // console.error(" ==== unblock entry", entry && entry.path)
45         if (!entry) return resume()
46         entry.on('end', unblockEntry)
47         if (dest) dest.add(entry)
48         else stream.emit('entry', entry)
49       })()
50
51       function resume () {
52         stream.removeListener('entry', saveEntry)
53         stream.removeListener('data', save)
54         stream.removeListener('end', save)
55
56         stream.pipe = orig
57         if (dest) stream.pipe(dest)
58
59         buf.forEach(function (b) {
60           if (b) stream.emit('data', b)
61           else stream.emit('end')
62         })
63
64         stream.resume()
65       }
66
67       return dest
68     }
69   })(stream.pipe)
70 }