From e1d3e9dc75fcae4bedbf2f9ce1e5aced2238a5e2 Mon Sep 17 00:00:00 2001 From: Omar El-Mihilmy Date: Wed, 3 Nov 2021 12:22:59 -0700 Subject: [PATCH] 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: https://github.com/nodejs/node/issues/40715 Refs: https://github.com/nodejs/node/pull/40716 --- lib/internal/fs/promises.js | 2 +- .../test-fs-promises-file-handle-read.js | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index b9c3b7cb407159..93b88b4cf8077c 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -521,7 +521,7 @@ async function read(handle, bufferOrOptions, offset, length, position) { } offset = bufferOrOptions.offset || 0; length = buffer.byteLength; - position = bufferOrOptions.position || null; + position = bufferOrOptions.position ?? null; } if (offset == null) { diff --git a/test/parallel/test-fs-promises-file-handle-read.js b/test/parallel/test-fs-promises-file-handle-read.js index 44ef2c6b815a3d..2eec89296a3c20 100644 --- a/test/parallel/test-fs-promises-file-handle-read.js +++ b/test/parallel/test-fs-promises-file-handle-read.js @@ -68,6 +68,27 @@ async function validateReadNoParams() { await fileHandle.read(); } +/** + * Validates that the zero position is respected after the position has been + * moved. The test iterates over the xyz chars twice making sure that the values + * are read from the correct position. + */ +async function validateReadWithPositionZero() { + const opts = { useConf: true }; + const filePath = fixtures.path('x.txt'); + const fileHandle = await open(filePath, 'r'); + const expectedSequence = ['x', 'y', 'z']; + + for (let i = 0; i < expectedSequence.length * 2; i++) { + const len = 1; + const pos = i % 3; + const buf = Buffer.alloc(len); + const { bytesRead } = await read(fileHandle, buf, 0, len, pos, opts); + assert.strictEqual(bytesRead, len); + assert.strictEqual(buf.toString(), expectedSequence[pos]); + } +} + (async function() { tmpdir.refresh(); @@ -78,4 +99,5 @@ async function validateReadNoParams() { await validateLargeRead({ useConf: false }); await validateLargeRead({ useConf: true }); await validateReadNoParams(); + await validateReadWithPositionZero(); })().then(common.mustCall());