diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 86e6924ca2104e..4b568b52b8d106 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -315,23 +315,24 @@ async function readFileHandle(filehandle, options) { throw new ERR_FS_FILE_TOO_LARGE(size); const chunks = []; - const chunkSize = size === 0 ? - kReadFileMaxChunkSize : - MathMin(size, kReadFileMaxChunkSize); + let isFirstChunk = true; + const firstChunkSize = size === 0 ? kReadFileMaxChunkSize : size; + const chunkSize = MathMin(firstChunkSize, kReadFileMaxChunkSize); let endOfFile = false; do { if (signal?.aborted) { throw lazyDOMException('The operation was aborted', 'AbortError'); } - const buf = Buffer.alloc(chunkSize); + const buf = Buffer.alloc(isFirstChunk ? firstChunkSize : chunkSize); const { bytesRead, buffer } = - await read(filehandle, buf, 0, chunkSize, -1); + await read(filehandle, buf, 0, buf.length, -1); endOfFile = bytesRead === 0; if (bytesRead > 0) ArrayPrototypePush(chunks, buffer.slice(0, bytesRead)); + isFirstChunk = false; } while (!endOfFile); - const result = Buffer.concat(chunks); + const result = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks); return options.encoding ? result.toString(options.encoding) : result; }