diff --git a/lib/fs.js b/lib/fs.js index c75bfedf73c4..07f5634d80a1 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1115,6 +1115,8 @@ function write(fd, buffer, offsetOrOptions, length, position, callback) { if (typeof position !== 'number') position = null; validateOffsetLengthWrite(offset, length, buffer.byteLength); + // V8 does not report -0 as an int32, which the binding requires. + length |= 0; const h = vfsState.handlers; if (h !== null) { @@ -1205,6 +1207,8 @@ function writeSync(fd, buffer, offsetOrOptions, length, position) { if (typeof length !== 'number') length = buffer.byteLength - offset; validateOffsetLengthWrite(offset, length, buffer.byteLength); + // V8 does not report -0 as an int32, which the binding requires. + length |= 0; const h = vfsState.handlers; if (h !== null) { diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 8507abcf0239..4032791d2388 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -1576,6 +1576,8 @@ async function write(handle, buffer, offsetOrOptions, length, position) { if (typeof position !== 'number') position = null; validateOffsetLengthWrite(offset, length, buffer.byteLength); + // V8 does not report -0 as an int32, which the binding requires. + length |= 0; const bytesWritten = (await PromisePrototypeThen( binding.writeBuffer(handle.fd, buffer, offset, diff --git a/test/parallel/test-fs-negative-zero.js b/test/parallel/test-fs-negative-zero.js index 66862762bfb3..c8cda8aba6bf 100644 --- a/test/parallel/test-fs-negative-zero.js +++ b/test/parallel/test-fs-negative-zero.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); const { spawnSync } = require('child_process'); @@ -45,3 +45,28 @@ assert.strictEqual(child.stdout.toString(), 'hello'); fs.watchFile(missing, { interval: -0 }, () => {}); fs.unwatchFile(missing); + +// A length of -0 writes nothing, like 0. +{ + const buffer = Buffer.from('abc'); + + const fd = fs.openSync(tmpdir.resolve('negative-zero-fd.txt'), 'w'); + assert.strictEqual(fs.writeSync(fd, buffer, 0, -0), 0); + assert.strictEqual(fs.writeSync(fd, buffer, { length: -0 }), 0); + fs.write(fd, buffer, 0, -0, common.mustSucceed((written) => { + assert.strictEqual(written, 0); + fs.write(fd, buffer, { length: -0 }, common.mustSucceed((written) => { + assert.strictEqual(written, 0); + fs.closeSync(fd); + })); + })); + + (async () => { + const handle = + await fs.promises.open(tmpdir.resolve('negative-zero-handle.txt'), 'w'); + assert.strictEqual((await handle.write(buffer, 0, -0)).bytesWritten, 0); + assert.strictEqual( + (await handle.write(buffer, { length: -0 })).bytesWritten, 0); + await handle.close(); + })().then(common.mustCall()); +}