Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
27 changes: 26 additions & 1 deletion test/parallel/test-fs-negative-zero.js
Original file line number Diff line number Diff line change
@@ -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');
Expand Down Expand Up @@ -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());
}
Loading