diff --git a/lib/internal/fs/sync_write_stream.js b/lib/internal/fs/sync_write_stream.js index 8fa5c56aaffc62..2666bf9ac511d9 100644 --- a/lib/internal/fs/sync_write_stream.js +++ b/lib/internal/fs/sync_write_stream.js @@ -23,8 +23,12 @@ ObjectSetPrototypeOf(SyncWriteStream.prototype, Writable.prototype); ObjectSetPrototypeOf(SyncWriteStream, Writable); SyncWriteStream.prototype._write = function(chunk, encoding, cb) { - writeSync(this.fd, chunk, 0, chunk.length); - cb(); + try { + writeSync(this.fd, chunk, 0, chunk.length); + cb(); + } catch (e) { + cb(e); + } return true; }; diff --git a/test/parallel/test-internal-fs-syncwritestream.js b/test/parallel/test-internal-fs-syncwritestream.js index bafa5fd8f4624f..884c363db52d70 100644 --- a/test/parallel/test-internal-fs-syncwritestream.js +++ b/test/parallel/test-internal-fs-syncwritestream.js @@ -74,3 +74,15 @@ const filename = path.join(tmpdir.path, 'sync-write-stream.txt'); assert.strictEqual(stream.fd, null); })); } + +// Verify write file failed trigger error event +{ + const fd = fs.openSync(filename, 'w'); + const stream = new SyncWriteStream(fd); + + assert.strictEqual(stream.fd, fd); + stream.on('error', common.mustCall()); + stream._write({}, common.mustCall((err) => { + assert(err); + })); +}