From fc9c6c3227609cdb5d615d0b95c8dc3d62ffc501 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 b7189573416899..9522d966673982 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -237,7 +237,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());