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); + })); +}