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

[v14.x backport] fs: improve fsPromises readFile performance #39838

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 4 additions & 6 deletions lib/fs.js
Expand Up @@ -24,10 +24,6 @@

'use strict';

// Most platforms don't allow reads or writes >= 2 GB.
// See https://github.com/libuv/libuv/pull/1501.
const kIoMaxLength = 2 ** 31 - 1;

// When using FSReqCallback, make sure to create the object only *after* all
// parameter validation has happened, so that the objects are not kept in memory
// in case they are created but never used due to an exception.
Expand Down Expand Up @@ -79,6 +75,10 @@ const { FSReqCallback, statValues } = binding;
const { toPathIfFileURL } = require('internal/url');
const internalUtil = require('internal/util');
const {
constants: {
kIoMaxLength,
kMaxUserId,
},
copyObject,
Dirent,
getDirents,
Expand Down Expand Up @@ -121,8 +121,6 @@ const {
validateInteger,
validateInt32
} = require('internal/validators');
// 2 ** 32 - 1
const kMaxUserId = 4294967295;

let truncateWarn = true;
let fs;
Expand Down
61 changes: 40 additions & 21 deletions lib/internal/fs/promises.js
@@ -1,18 +1,9 @@
'use strict';

// Most platforms don't allow reads or writes >= 2 GB.
// See https://github.com/libuv/libuv/pull/1501.
const kIoMaxLength = 2 ** 31 - 1;

// Note: This is different from kReadFileBufferLength used for non-promisified
// fs.readFile.
const kReadFileMaxChunkSize = 2 ** 14;
const kWriteFileMaxChunkSize = 2 ** 14;

// 2 ** 32 - 1
const kMaxUserId = 4294967295;

const {
ArrayPrototypePush,
Error,
MathMax,
MathMin,
Expand Down Expand Up @@ -44,6 +35,12 @@ const {
const { isArrayBufferView } = require('internal/util/types');
const { rimrafPromises } = require('internal/fs/rimraf');
const {
constants: {
kIoMaxLength,
kMaxUserId,
kReadFileBufferLength,
kReadFileUnknownBufferLength,
},
copyObject,
getDirents,
getOptions,
Expand Down Expand Up @@ -296,24 +293,46 @@ async function readFileHandle(filehandle, options) {
if (size > kIoMaxLength)
throw new ERR_FS_FILE_TOO_LARGE(size);

const chunks = [];
const chunkSize = size === 0 ?
kReadFileMaxChunkSize :
MathMin(size, kReadFileMaxChunkSize);
let endOfFile = false;
let totalRead = 0;
const noSize = size === 0;
const buffers = [];
const fullBuffer = noSize ? undefined : Buffer.allocUnsafeSlow(size);
do {
if (signal && signal.aborted) {
throw lazyDOMException('The operation was aborted', 'AbortError');
}
const buf = Buffer.alloc(chunkSize);
const { bytesRead, buffer } =
await read(filehandle, buf, 0, chunkSize, -1);
endOfFile = bytesRead === 0;
if (bytesRead > 0)
chunks.push(buffer.slice(0, bytesRead));
let buffer;
let offset;
let length;
if (noSize) {
buffer = Buffer.allocUnsafeSlow(kReadFileUnknownBufferLength);
offset = 0;
length = kReadFileUnknownBufferLength;
} else {
buffer = fullBuffer;
offset = totalRead;
length = MathMin(size - totalRead, kReadFileBufferLength);
}

const bytesRead = (await binding.read(filehandle.fd, buffer, offset,
length, -1, kUsePromises)) || 0;
totalRead += bytesRead;
endOfFile = bytesRead === 0 || totalRead === size;
if (noSize && bytesRead > 0) {
const isBufferFull = bytesRead === kReadFileUnknownBufferLength;
const chunkBuffer = isBufferFull ? buffer : buffer.slice(0, bytesRead);
ArrayPrototypePush(buffers, chunkBuffer);
}
} while (!endOfFile);

const result = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
let result;
if (size > 0) {
result = totalRead === size ? fullBuffer : fullBuffer.slice(0, totalRead);
} else {
result = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers,
totalRead);
}

return options.encoding ? result.toString(options.encoding) : result;
}
Expand Down
16 changes: 7 additions & 9 deletions lib/internal/fs/read_file_context.js
Expand Up @@ -4,6 +4,13 @@ const {
MathMin,
} = primordials;

const {
constants: {
kReadFileBufferLength,
kReadFileUnknownBufferLength,
}
} = require('internal/fs/utils');

const { Buffer } = require('buffer');

const { FSReqCallback, close, read } = internalBinding('fs');
Expand All @@ -18,15 +25,6 @@ const lazyDOMException = hideStackFrames((message, name) => {
return new DOMException(message, name);
});

// Use 64kb in case the file type is not a regular file and thus do not know the
// actual file size. Increasing the value further results in more frequent over
// allocation for small files and consumes CPU time and memory that should be
// used else wise.
// Use up to 512kb per read otherwise to partition reading big files to prevent
// blocking other threads in case the available threads are all in use.
const kReadFileUnknownBufferLength = 64 * 1024;
const kReadFileBufferLength = 512 * 1024;

function readFileAfterRead(err, bytesRead) {
const context = this.context;

Expand Down
21 changes: 21 additions & 0 deletions lib/internal/fs/utils.js
Expand Up @@ -113,6 +113,21 @@ const kMaximumCopyMode = COPYFILE_EXCL |
COPYFILE_FICLONE |
COPYFILE_FICLONE_FORCE;

// Most platforms don't allow reads or writes >= 2 GB.
// See https://github.com/libuv/libuv/pull/1501.
const kIoMaxLength = 2 ** 31 - 1;

// Use 64kb in case the file type is not a regular file and thus do not know the
// actual file size. Increasing the value further results in more frequent over
// allocation for small files and consumes CPU time and memory that should be
// used else wise.
// Use up to 512kb per read otherwise to partition reading big files to prevent
// blocking other threads in case the available threads are all in use.
const kReadFileUnknownBufferLength = 64 * 1024;
const kReadFileBufferLength = 512 * 1024;

const kMaxUserId = 2 ** 32 - 1;

const isWindows = process.platform === 'win32';

let fs;
Expand Down Expand Up @@ -815,6 +830,12 @@ const validatePosition = hideStackFrames((position, name) => {
});

module.exports = {
constants: {
kIoMaxLength,
kMaxUserId,
kReadFileBufferLength,
kReadFileUnknownBufferLength,
},
assertEncoding,
BigIntStats, // for testing
copyObject,
Expand Down
15 changes: 10 additions & 5 deletions test/parallel/test-fs-promises-file-handle-readFile.js
Expand Up @@ -11,7 +11,7 @@ const {
open,
readFile,
writeFile,
truncate
truncate,
} = fs.promises;
const path = require('path');
const tmpdir = require('../common/tmpdir');
Expand Down Expand Up @@ -65,6 +65,7 @@ async function doReadAndCancel() {
await assert.rejects(readFile(fileHandle, { signal }), {
name: 'AbortError'
});
await fileHandle.close();
}

// Signal aborted on first tick
Expand All @@ -75,10 +76,11 @@ async function doReadAndCancel() {
fs.writeFileSync(filePathForHandle, buffer);
const controller = new AbortController();
const { signal } = controller;
tick(1, () => controller.abort());
process.nextTick(() => controller.abort());
await assert.rejects(readFile(fileHandle, { signal }), {
name: 'AbortError'
});
}, 'tick-0');
await fileHandle.close();
}

// Signal aborted right before buffer read
Expand All @@ -91,10 +93,12 @@ async function doReadAndCancel() {

const controller = new AbortController();
const { signal } = controller;
tick(2, () => controller.abort());
tick(1, () => controller.abort());
await assert.rejects(fileHandle.readFile({ signal, encoding: 'utf8' }), {
name: 'AbortError'
});
}, 'tick-1');

await fileHandle.close();
}

// Validate file size is within range for reading
Expand All @@ -112,6 +116,7 @@ async function doReadAndCancel() {
name: 'RangeError',
code: 'ERR_FS_FILE_TOO_LARGE'
});
await fileHandle.close();
}
}

Expand Down