forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
pipe is similar to pipeline however it supports stream composition. Refs: nodejs#32020
- Loading branch information
Showing
2 changed files
with
102 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
'use strict'; | ||
|
||
const pipeline = require('internal/streams/pipeline'); | ||
const Duplex = require('internal/streams/duplex'); | ||
const { destroyer } = require('internal/streams/destroy'); | ||
|
||
module.exports = function pipe(...streams) { | ||
let onclose; | ||
let ret; | ||
|
||
const r = pipeline(streams, function(err) { | ||
if (onclose) { | ||
const cb = onclose; | ||
onclose = null; | ||
cb(err); | ||
} else { | ||
ret.destroy(err); | ||
} | ||
}); | ||
const w = streams[0]; | ||
|
||
const writable = w.writable; | ||
const readable = r.readable; | ||
const objectMode = w.readableObjectMode; | ||
|
||
ret = new Duplex({ | ||
writable, | ||
readable, | ||
objectMode, | ||
highWaterMark: 1 | ||
}); | ||
|
||
if (writable) { | ||
let ondrain; | ||
let onfinish; | ||
|
||
ret._write = function(chunk, encoding, callback) { | ||
if (w.write(chunk, encoding)) { | ||
callback(); | ||
} else { | ||
ondrain = callback; | ||
} | ||
}; | ||
|
||
ret._final = function(chunk, encoding, callback) { | ||
w.end(chunk, encoding); | ||
onfinish = callback; | ||
}; | ||
|
||
ret.on('drain', function () { | ||
if (ondrain) { | ||
const cb = ondrain; | ||
ondrain = null; | ||
cb(); | ||
} | ||
}); | ||
|
||
ret.on('finish', function () { | ||
if (onfinish) { | ||
const cb = onfinish | ||
onfinish = null; | ||
cb(); | ||
} | ||
}); | ||
} | ||
|
||
if (readable) { | ||
let onreadable; | ||
|
||
r.on('readable', function () { | ||
if (onreadable) { | ||
const cb = onreadable | ||
onreadable = null; | ||
cb(); | ||
} | ||
}); | ||
|
||
ret._read = function () { | ||
while (true) { | ||
const buf = r.read(); | ||
|
||
if (buf === null) { | ||
onreadable = ret._read; | ||
return; | ||
} | ||
|
||
if (!ret.push(buf)) { | ||
return; | ||
} | ||
} | ||
}; | ||
} | ||
|
||
ret._destroy = function(err, callback) { | ||
onclose = callback; | ||
for (const stream of streams) { | ||
destroyer(stream, err); | ||
} | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters