Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream: finish pipeline if dst closes before src #43701

Merged
merged 2 commits into from
Jul 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/internal/streams/pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const {
ERR_INVALID_RETURN_VALUE,
ERR_MISSING_ARGS,
ERR_STREAM_DESTROYED,
ERR_STREAM_PREMATURE_CLOSE,
},
AbortError,
} = require('internal/errors');
Expand Down Expand Up @@ -344,13 +345,24 @@ function pipelineImpl(streams, callback, opts) {
}

function pipe(src, dst, finish, { end }) {
let ended = false;
dst.on('close', () => {
if (!ended) {
// Finish if the destination closes before the source has completed.
finish(new ERR_STREAM_PREMATURE_CLOSE());
}
});

src.pipe(dst, { end });

if (end) {
// Compat. Before node v10.12.0 stdio used to throw an error so
// pipe() did/does not end() stdio destinations.
// Now they allow it but "secretly" don't close the underlying fd.
src.once('end', () => dst.end());
src.once('end', () => {
ended = true;
dst.end();
});
} else {
finish();
}
Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-stream-pipeline-duplex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

const common = require('../common');
const { pipeline, Duplex, PassThrough } = require('stream');
const assert = require('assert');

const remote = new PassThrough();
const local = new Duplex({
read() {},
write(chunk, enc, callback) {
callback();
}
});

pipeline(remote, local, remote, common.mustCall((err) => {
assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE');
}));

setImmediate(() => {
remote.end();
});