Skip to content

Commit fc328f1

Browse files
mihilmyrichardlau
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 0231ffa commit fc328f1

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

lib/internal/fs/promises.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ async function read(handle, bufferOrOptions, offset, length, position) {
399399
}
400400
offset = bufferOrOptions.offset || 0;
401401
length = buffer.byteLength;
402-
position = bufferOrOptions.position || null;
402+
position = bufferOrOptions.position ?? null;
403403
}
404404

405405
if (offset == null) {

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

+19
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,24 @@ async function validateReadNoParams() {
6868
}
6969

7070
let useConf = false;
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+
}
7189

7290
(async function() {
7391
for (const value of [false, true]) {
@@ -80,4 +98,5 @@ let useConf = false;
8098
.then(common.mustCall());
8199
}
82100
await validateReadNoParams();
101+
await validateReadWithPositionZero();
83102
})().then(common.mustCall());

0 commit comments

Comments
 (0)