|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const pipeline = require('internal/streams/pipeline'); |
| 4 | +const Duplex = require('internal/streams/duplex'); |
| 5 | +const { destroyer } = require('internal/streams/destroy'); |
| 6 | + |
| 7 | +module.exports = function pipe(...streams) { |
| 8 | + let ondrain; |
| 9 | + let onfinish; |
| 10 | + let onreadable; |
| 11 | + let onclose; |
| 12 | + let ret; |
| 13 | + |
| 14 | + const r = pipeline(streams, function(err) { |
| 15 | + if (onclose) { |
| 16 | + const cb = onclose; |
| 17 | + onclose = null; |
| 18 | + cb(err); |
| 19 | + } else { |
| 20 | + ret.destroy(err); |
| 21 | + } |
| 22 | + }); |
| 23 | + const w = streams[0]; |
| 24 | + |
| 25 | + const writable = w.writable; |
| 26 | + const readable = r.readable; |
| 27 | + const objectMode = w.readableObjectMode; |
| 28 | + |
| 29 | + ret = new Duplex({ |
| 30 | + writable, |
| 31 | + readable, |
| 32 | + objectMode, |
| 33 | + highWaterMark: 1 |
| 34 | + }); |
| 35 | + |
| 36 | + if (writable) { |
| 37 | + ret._write = function(chunk, encoding, callback) { |
| 38 | + if (w.write(chunk, encoding)) { |
| 39 | + callback(); |
| 40 | + } else { |
| 41 | + ondrain = callback; |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + ret._final = function(callback) { |
| 46 | + w.end(); |
| 47 | + onfinish = callback; |
| 48 | + }; |
| 49 | + |
| 50 | + ret.on('drain', function() { |
| 51 | + if (ondrain) { |
| 52 | + const cb = ondrain; |
| 53 | + ondrain = null; |
| 54 | + cb(); |
| 55 | + } |
| 56 | + }); |
| 57 | + |
| 58 | + ret.on('finish', function() { |
| 59 | + if (onfinish) { |
| 60 | + const cb = onfinish; |
| 61 | + onfinish = null; |
| 62 | + cb(); |
| 63 | + } |
| 64 | + }); |
| 65 | + |
| 66 | + // Writable.write unfortunately checks buffering before |
| 67 | + // writing, and not after due to https://github.com/nodejs/node/pull/35941. |
| 68 | + // We need to override this in order to avoid buffering overhead. |
| 69 | + ret.write = function write (chunk, encoding, cb) { |
| 70 | + return Duplex.prototype.write.call(ret, chunk, encoding, cb) && !ondrain; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + if (readable) { |
| 75 | + r.on('readable', function() { |
| 76 | + if (onreadable) { |
| 77 | + const cb = onreadable; |
| 78 | + onreadable = null; |
| 79 | + cb(); |
| 80 | + } |
| 81 | + }); |
| 82 | + |
| 83 | + ret._read = function() { |
| 84 | + while (true) { |
| 85 | + const buf = r.read(); |
| 86 | + |
| 87 | + if (buf === null) { |
| 88 | + onreadable = ret._read; |
| 89 | + return; |
| 90 | + } |
| 91 | + |
| 92 | + if (!ret.push(buf)) { |
| 93 | + return; |
| 94 | + } |
| 95 | + } |
| 96 | + }; |
| 97 | + } |
| 98 | + |
| 99 | + ret._destroy = function(err, callback) { |
| 100 | + onclose = callback; |
| 101 | + onreadable = null; |
| 102 | + ondrain = null; |
| 103 | + onfinish = null; |
| 104 | + destroyer(r, err); |
| 105 | + }; |
| 106 | +}; |
0 commit comments