Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs: improve promises.readFile performance #37127

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down