| 1 |
'use strict'; |
| 2 |
|
| 3 |
var through = require('through2'); |
| 4 |
|
| 5 |
function forward(chunk, enc, cb) { |
| 6 |
cb(null, chunk); |
| 7 |
} |
| 8 |
|
| 9 |
function toThrough(readable) { |
| 10 |
|
| 11 |
var opts = { |
| 12 |
objectMode: readable._readableState.objectMode, |
| 13 |
highWaterMark: readable._readableState.highWaterMark, |
| 14 |
}; |
| 15 |
|
| 16 |
function flush(cb) { |
| 17 |
var self = this; |
| 18 |
|
| 19 |
readable.on('readable', onReadable); |
| 20 |
readable.on('end', cb); |
| 21 |
|
| 22 |
function onReadable() { |
| 23 |
var chunk; |
| 24 |
while (chunk = readable.read()) { |
| 25 |
self.push(chunk); |
| 26 |
} |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
var wrapper = through(opts, forward, flush); |
| 31 |
|
| 32 |
var shouldFlow = true; |
| 33 |
wrapper.once('pipe', onPipe); |
| 34 |
wrapper.on('newListener', onListener); |
| 35 |
readable.on('error', wrapper.emit.bind(wrapper, 'error')); |
| 36 |
|
| 37 |
function onListener(event) { |
| 38 |
// Once we've seen the data or readable event, check if we need to flow |
| 39 |
if (event === 'data' || event === 'readable') { |
| 40 |
maybeFlow(); |
| 41 |
this.removeListener('newListener', onListener); |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
function onPipe() { |
| 46 |
// If the wrapper is piped, disable flow |
| 47 |
shouldFlow = false; |
| 48 |
} |
| 49 |
|
| 50 |
function maybeFlow() { |
| 51 |
// If we need to flow, end the stream which triggers flush |
| 52 |
if (shouldFlow) { |
| 53 |
wrapper.end(); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
return wrapper; |
| 58 |
} |
| 59 |
|
| 60 |
module.exports = toThrough; |