Skip to content

Commit 0377edc

Browse files
mihilmydanielleadams
authored andcommitted
fs: nullish coalescing to respect zero positional reads
When the file read position is moved passing zero is not respected and `null` is used instead. PR fixes the issues by using nullish coalescing which will return the rhs only when the lhs is `null` or `undefined`; respecting the zero. Fixes: #40715 PR-URL: #40716 Fixes: #40699 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Tobias Nießen <tniessen@tnie.de> Reviewed-By: Evan Lucas <evanlucas@me.com>
1 parent 86bbb42 commit 0377edc

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/internal/fs/promises.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ async function read(handle, bufferOrOptions, offset, length, position) {
469469
}
470470
offset = bufferOrOptions.offset || 0;
471471
length = buffer.byteLength;
472-
position = bufferOrOptions.position || null;
472+
position = bufferOrOptions.position ?? null;
473473
}
474474

475475
if (offset == null) {

test/parallel/test-fs-promises-file-handle-read.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,25 @@ async function validateReadNoParams() {
6868
await fileHandle.read();
6969
}
7070

71+
// Validates that the zero position is respected after the position has been
72+
// moved. The test iterates over the xyz chars twice making sure that the values
73+
// are read from the correct position.
74+
async function validateReadWithPositionZero() {
75+
const opts = { useConf: true };
76+
const filePath = fixtures.path('x.txt');
77+
const fileHandle = await open(filePath, 'r');
78+
const expectedSequence = ['x', 'y', 'z'];
79+
80+
for (let i = 0; i < expectedSequence.length * 2; i++) {
81+
const len = 1;
82+
const pos = i % 3;
83+
const buf = Buffer.alloc(len);
84+
const { bytesRead } = await read(fileHandle, buf, 0, len, pos, opts);
85+
assert.strictEqual(bytesRead, len);
86+
assert.strictEqual(buf.toString(), expectedSequence[pos]);
87+
}
88+
}
89+
7190

7291
(async function() {
7392
tmpdir.refresh();
@@ -78,4 +97,5 @@ async function validateReadNoParams() {
7897
await validateLargeRead({ useConf: false });
7998
await validateLargeRead({ useConf: true });
8099
await validateReadNoParams();
100+
await validateReadWithPositionZero();
81101
})().then(common.mustCall());

0 commit comments

Comments
 (0)