From 927888bfec581cd7fc195350186906893a251b61 Mon Sep 17 00:00:00 2001 From: killagu Date: Wed, 10 May 2023 19:55:11 +0800 Subject: [PATCH] fs: call the callback with an error if writeSync fails Catch SyncWriteStream write file error. Fixes: https://github.com/nodejs/node/issues/47948 Signed-off-by: killagu --- lib/internal/fs/sync_write_stream.js | 8 ++++++-- test/parallel/test-internal-fs-syncwritestream.js | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/internal/fs/sync_write_stream.js b/lib/internal/fs/sync_write_stream.js index 8fa5c56aaffc62..f8fbade88393b4 100644 --- a/lib/internal/fs/sync_write_stream.js +++ b/lib/internal/fs/sync_write_stream.js @@ -23,9 +23,13 @@ ObjectSetPrototypeOf(SyncWriteStream.prototype, Writable.prototype); ObjectSetPrototypeOf(SyncWriteStream, Writable); SyncWriteStream.prototype._write = function(chunk, encoding, cb) { - writeSync(this.fd, chunk, 0, chunk.length); + try { + writeSync(this.fd, chunk, 0, chunk.length); + } catch (e) { + cb(e); + return; + } cb(); - return true; }; SyncWriteStream.prototype._destroy = function(err, cb) { diff --git a/test/parallel/test-internal-fs-syncwritestream.js b/test/parallel/test-internal-fs-syncwritestream.js index bafa5fd8f4624f..11a32682017e46 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 that an error on _write() triggers an 'error' event. +{ + const fd = fs.openSync(filename, 'w'); + const stream = new SyncWriteStream(fd); + + assert.strictEqual(stream.fd, fd); + stream._write({}, null, common.mustCall((err) => { + assert(err); + fs.closeSync(fd); + })); +}