Skip to content

Commit

Permalink
fs: do not emit 'finish' before 'open' on write empty file
Browse files Browse the repository at this point in the history
'finish' could previously be emitted before the file has been
created when ending a write stream without having written any
data.

Refs: expressjs/multer#238

PR-URL: #29930
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Jeremiah Senkpiel <fishrock123@rocketmail.com>
  • Loading branch information
ronag authored and targos committed Oct 18, 2019
1 parent b59209b commit 8ebc945
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/internal/fs/streams.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
14 changes: 14 additions & 0 deletions test/parallel/test-fs-write-stream-end.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}));
}

0 comments on commit 8ebc945

Please sign in to comment.