From ba45367830f6a5c73c20e64ee71265d3aa4af719 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 3674a71f92ba15..673dab34fb7473 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -284,6 +284,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); + })); +}