Skip to content

Commit e1d3e9d

Browse files
committed
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 Refs: #40716
1 parent 8fce09e commit e1d3e9d

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lib/internal/fs/promises.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -521,7 +521,7 @@ async function read(handle, bufferOrOptions, offset, length, position) {
521521
}
522522
offset = bufferOrOptions.offset || 0;
523523
length = buffer.byteLength;
524-
position = bufferOrOptions.position || null;
524+
position = bufferOrOptions.position ?? null;
525525
}
526526

527527
if (offset == null) {

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

+22
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,27 @@ async function validateReadNoParams() {
6868
await fileHandle.read();
6969
}
7070

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

7293
(async function() {
7394
tmpdir.refresh();
@@ -78,4 +99,5 @@ async function validateReadNoParams() {
7899
await validateLargeRead({ useConf: false });
79100
await validateLargeRead({ useConf: true });
80101
await validateReadNoParams();
102+
await validateReadWithPositionZero();
81103
})().then(common.mustCall());

0 commit comments

Comments
 (0)