From 8ebc94562cb570a8f2331675dc83c37fd9fe7417 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Fri, 11 Oct 2019 12:12:18 +0200 Subject: [PATCH] fs: do not emit 'finish' before 'open' on write empty file 'finish' could previously be emitted before the file has been created when ending a write stream without having written any data. Refs: https://github.com/expressjs/multer/issues/238 PR-URL: https://github.com/nodejs/node/pull/29930 Reviewed-By: Rich Trott Reviewed-By: Matteo Collina Reviewed-By: Luigi Pinca Reviewed-By: Anna Henningsen Reviewed-By: Jeremiah Senkpiel --- lib/internal/fs/streams.js | 6 ++++++ test/parallel/test-fs-write-stream-end.js | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index 110ad114930fca..210c1ad1ae1a8c 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -272,6 +272,12 @@ Object.setPrototypeOf(WriteStream.prototype, Writable.prototype); Object.setPrototypeOf(WriteStream, Writable); WriteStream.prototype._final = function(callback) { + if (typeof this.fd !== 'number') { + return this.once('open', function() { + this._final(callback); + }); + } + if (this.autoClose) { this.destroy(); } diff --git a/test/parallel/test-fs-write-stream-end.js b/test/parallel/test-fs-write-stream-end.js index 36e7cb5504cab0..daaff6a2530346 100644 --- a/test/parallel/test-fs-write-stream-end.js +++ b/test/parallel/test-fs-write-stream-end.js @@ -44,3 +44,17 @@ tmpdir.refresh(); assert.strictEqual(content, 'a\n'); })); } + +{ + const file = path.join(tmpdir.path, 'write-end-test2.txt'); + const stream = fs.createWriteStream(file); + stream.end(); + + let calledOpen = false; + stream.on('open', () => { + calledOpen = true; + }); + stream.on('finish', common.mustCall(() => { + assert.strictEqual(calledOpen, true); + })); +}