Skip to content

Commit

Permalink
fs: defer the writestream 'open' event by a nextTick
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Mar 7, 2024
1 parent 3aa0658 commit f6e2284
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/internal/fs/streams.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,19 @@ function _construct(callback) {
} else {
stream.fd = fd;
callback();
stream.emit('open', stream.fd);
stream.emit('ready');
// Ready must be deferred to the next tick, because callback will schedule
// some microtick work that we need to complete first.
process.nextTick(emitReady, stream);
}
});
}
}

function emitReady(stream) {
stream.emit('open', stream.fd);
stream.emit('ready');
}

// This generates an fs operations structure for a FileHandle
const FileHandleOperations = (handle) => {
return {
Expand Down
27 changes: 27 additions & 0 deletions test/parallel/test-fs-writestream-open-write.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict'

const common = require('../common');
const { strictEqual } = require('assert');
const { tmpdir } = require('os');
const { join } = require('path');
const fs = require('fs');

// Regression test for https://github.com/nodejs/node/issues/51993

const file = join(tmpdir(), `test-fs-writestream-open-write-${process.pid}.txt`);

const w = fs.createWriteStream(file);

w.on('open', common.mustCall(() => {
w.write('hello');

process.nextTick(() => {
w.write('world');
w.end();
});
}));

w.on('close', common.mustCall(() => {
strictEqual(fs.readFileSync(file, 'utf8'), 'helloworld');
fs.unlinkSync(file);
}));

0 comments on commit f6e2284

Please sign in to comment.