Skip to content

Commit a65218f

Browse files
committed
stream: try to wait for flush to complete before 'finish'
Due to compat reasons Transform streams don't always wait for flush to complete before finishing the stream. Try to wait when possible, i.e. when the user does not override _final. Fixes: #34274 PR-URL: #34314 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Zeyu Yang <himself65@outlook.com>
1 parent e44855d commit a65218f

File tree

3 files changed

+49
-2
lines changed

3 files changed

+49
-2
lines changed

lib/_stream_transform.js

+20-2
Original file line numberDiff line numberDiff line change
@@ -106,24 +106,42 @@ function Transform(options) {
106106
this.on('prefinish', prefinish);
107107
}
108108

109-
function prefinish() {
109+
function final(cb) {
110110
if (typeof this._flush === 'function' && !this.destroyed) {
111111
this._flush((er, data) => {
112112
if (er) {
113-
this.destroy(er);
113+
if (cb) {
114+
cb(er);
115+
} else {
116+
this.destroy(er);
117+
}
114118
return;
115119
}
116120

117121
if (data != null) {
118122
this.push(data);
119123
}
120124
this.push(null);
125+
if (cb) {
126+
cb();
127+
}
121128
});
122129
} else {
123130
this.push(null);
131+
if (cb) {
132+
cb();
133+
}
134+
}
135+
}
136+
137+
function prefinish() {
138+
if (this._final !== final) {
139+
final.call(this);
124140
}
125141
}
126142

143+
Transform.prototype._final = final;
144+
127145
Transform.prototype._transform = function(chunk, encoding, callback) {
128146
throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()');
129147
};

lib/zlib.js

+5
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,11 @@ ZlibBase.prototype._flush = function(callback) {
323323
this._transform(Buffer.alloc(0), '', callback);
324324
};
325325

326+
// Force Transform compat behavior.
327+
ZlibBase.prototype._final = function(callback) {
328+
callback();
329+
};
330+
326331
// If a flush is scheduled while another flush is still pending, a way to figure
327332
// out which one is the "stronger" flush is needed.
328333
// This is currently only used to figure out which flush flag to use for the

test/parallel/test-stream-pipeline.js

+24
Original file line numberDiff line numberDiff line change
@@ -1231,3 +1231,27 @@ const net = require('net');
12311231
assert.strictEqual(res, 'helloworld');
12321232
}));
12331233
}
1234+
1235+
{
1236+
let flushed = false;
1237+
const makeStream = () =>
1238+
new Transform({
1239+
transform: (chunk, enc, cb) => cb(null, chunk),
1240+
flush: (cb) =>
1241+
setTimeout(() => {
1242+
flushed = true;
1243+
cb(null);
1244+
}, 1),
1245+
});
1246+
1247+
const input = new Readable();
1248+
input.push(null);
1249+
1250+
pipeline(
1251+
input,
1252+
makeStream(),
1253+
common.mustCall(() => {
1254+
assert.strictEqual(flushed, true);
1255+
}),
1256+
);
1257+
}

0 commit comments

Comments
 (0)