Skip to content

Commit 42eaf45

Browse files
committed
streams: add stream.pipe
pipe is similar to pipeline however it supports stream composition. Refs: nodejs#32020
1 parent 4e17ffc commit 42eaf45

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

lib/internal/streams/pipelinify.js

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const pipeline = require('internal/streams/pipeline');
4+
const Duplex = require('internal/streams/duplex');
5+
6+
module.exports = function pipe(...streams) {
7+
let ondrain;
8+
let onfinish;
9+
let onclose;
10+
let onreadable;
11+
let ret;
12+
13+
const r = pipeline(streams, function(err) {
14+
if (onclose) {
15+
const cb = onclose;
16+
onclose = null;
17+
cb(err);
18+
} else {
19+
ret.destroy(err);
20+
}
21+
});
22+
const w = streams[0];
23+
24+
const writable = w.writable;
25+
const readable = r.readable;
26+
const objectMode = w.readableObjectMode;
27+
28+
ret = new Duplex({
29+
writable,
30+
readable,
31+
objectMode,
32+
highWaterMark: 1
33+
});
34+
35+
if (writable) {
36+
ret._write = function(chunk, encoding, callback) {
37+
if (w.write(chunk, encoding)) {
38+
callback();
39+
} else {
40+
ondrain = callback;
41+
}
42+
};
43+
44+
ret._final = function(chunk, encoding, callback) {
45+
w.end(chunk, encoding);
46+
onfinish = callback;
47+
};
48+
49+
ret.on('drain', function () {
50+
if (ondrain) {
51+
const cb = ondrain;
52+
ondrain = null;
53+
cb();
54+
}
55+
});
56+
57+
ret.on('finish', function () {
58+
if (onfinish) {
59+
const cb = onfinish
60+
onfinish = null;
61+
cb();
62+
}
63+
});
64+
}
65+
66+
if (readable) {
67+
onreadable = function () {
68+
while (true) {
69+
const buf = r.read();
70+
71+
if (buf === null) {
72+
r.once('readable', onreadable);
73+
return;
74+
}
75+
76+
if (!ret.push(buf)) {
77+
return;
78+
}
79+
}
80+
}
81+
82+
ret._read = onreadable;
83+
}
84+
85+
ret._destroy = function(err, callback) {
86+
onclose = callback;
87+
streams[0].destroy(err);
88+
};
89+
}

lib/stream.js

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const {
3030
} = require('internal/util');
3131

3232
const pipeline = require('internal/streams/pipeline');
33+
const pipelinify = require('internal/streams/pipelinify');
3334
const eos = require('internal/streams/end-of-stream');
3435
const internalBuffer = require('internal/buffer');
3536

@@ -42,6 +43,7 @@ Stream.Duplex = require('internal/streams/duplex');
4243
Stream.Transform = require('internal/streams/transform');
4344
Stream.PassThrough = require('internal/streams/passthrough');
4445
Stream.pipeline = pipeline;
46+
Stream.pipelinify = pipelinify;
4547
const { addAbortSignal } = require('internal/streams/add-abort-signal');
4648
Stream.addAbortSignal = addAbortSignal;
4749
Stream.finished = eos;

0 commit comments

Comments
 (0)