From 2c2b3ba39cf7668eb0b0eda8a6e3626ac2a511fd Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Thu, 16 Jan 2020 18:42:54 +0100 Subject: [PATCH] fs: do not emit 'close' twice if emitClose enabled fs streams have some backwards compat behavior that does not behave well if emitClose: true is passed in options. This fixes this edge case until the backwards compat is removed. PR-URL: https://github.com/nodejs/node/pull/31383 Fixes: https://github.com/nodejs/node/issues/31366 Reviewed-By: Luigi Pinca Reviewed-By: Rich Trott --- lib/internal/fs/streams.js | 3 ++- test/parallel/test-file-write-stream4.js | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-file-write-stream4.js diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index 456b57d2af8f9a..14d6ea391d00c2 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -269,7 +269,8 @@ function closeFsStream(stream, cb, err) { er = er || err; cb(er); stream.closed = true; - if (!er) + const s = stream._writableState || stream._readableState; + if (!er && !s.emitClose) stream.emit('close'); }); diff --git a/test/parallel/test-file-write-stream4.js b/test/parallel/test-file-write-stream4.js new file mode 100644 index 00000000000000..2a81efcb66756f --- /dev/null +++ b/test/parallel/test-file-write-stream4.js @@ -0,0 +1,21 @@ +'use strict'; + +// Test that 'close' emits once and not twice when `emitClose: true` is set. +// Refs: https://github.com/nodejs/node/issues/31366 + +const common = require('../common'); +const path = require('path'); +const fs = require('fs'); + +const tmpdir = require('../common/tmpdir'); +tmpdir.refresh(); + +const filepath = path.join(tmpdir.path, 'write_pos.txt'); + +const fileReadStream = fs.createReadStream(process.execPath); +const fileWriteStream = fs.createWriteStream(filepath, { + emitClose: true +}); + +fileReadStream.pipe(fileWriteStream); +fileWriteStream.on('close', common.mustCall());