Skip to content

Commit cb1f218

Browse files
committed
fs: improve performance of recursive directory read
Fixes: #58892 Refs: #52663 Signed-off-by: avivkeller <me@aviv.sh>
1 parent 05a8e91 commit cb1f218

12 files changed

Lines changed: 1023 additions & 134 deletions
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const fs = require('fs');
5+
const path = require('path');
6+
const assert = require('assert');
7+
8+
const bench = common.createBenchmark(main, {
9+
n: [10],
10+
dir: ['lib', 'test/parallel', 'test'],
11+
mode: ['sync', 'callback', 'promise'],
12+
withFileTypes: ['true', 'false'],
13+
});
14+
15+
async function main({ n, dir, mode, withFileTypes }) {
16+
withFileTypes = withFileTypes === 'true';
17+
const fullPath = path.resolve(__dirname, '../../', dir);
18+
const options = { recursive: true, withFileTypes };
19+
let entries;
20+
21+
bench.start();
22+
switch (mode) {
23+
case 'sync':
24+
for (let i = 0; i < n; i++) {
25+
entries = fs.readdirSync(fullPath, options);
26+
}
27+
break;
28+
case 'callback':
29+
for (let i = 0; i < n; i++) {
30+
entries = await new Promise((resolve, reject) => {
31+
fs.readdir(fullPath, options, (err, result) => {
32+
if (err) reject(err);
33+
else resolve(result);
34+
});
35+
});
36+
}
37+
break;
38+
case 'promise':
39+
for (let i = 0; i < n; i++) {
40+
entries = await fs.promises.readdir(fullPath, options);
41+
}
42+
break;
43+
}
44+
bench.end(n);
45+
46+
assert.ok(entries.length > 0);
47+
}

‎benchmark/fs/bench-readdir.js‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,16 @@ const bench = common.createBenchmark(main, {
88
n: [10],
99
dir: [ 'lib', 'test/parallel'],
1010
withFileTypes: ['true', 'false'],
11-
recursive: ['true', 'false'],
1211
});
1312

14-
function main({ n, dir, withFileTypes, recursive }) {
13+
function main({ n, dir, withFileTypes }) {
1514
withFileTypes = withFileTypes === 'true';
16-
recursive = recursive === 'true';
1715
const fullPath = path.resolve(__dirname, '../../', dir);
1816
bench.start();
1917
(function r(cntr) {
2018
if (cntr-- <= 0)
2119
return bench.end(n);
22-
fs.readdir(fullPath, { withFileTypes, recursive }, () => {
20+
fs.readdir(fullPath, { withFileTypes }, () => {
2321
r(cntr);
2422
});
2523
}(n));

‎benchmark/fs/bench-readdirSync.js‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,15 @@ const bench = common.createBenchmark(main, {
88
n: [10],
99
dir: [ 'lib', 'test/parallel'],
1010
withFileTypes: ['true', 'false'],
11-
recursive: ['true', 'false'],
1211
});
1312

1413

15-
function main({ n, dir, withFileTypes, recursive }) {
14+
function main({ n, dir, withFileTypes }) {
1615
withFileTypes = withFileTypes === 'true';
17-
recursive = recursive === 'true';
1816
const fullPath = path.resolve(__dirname, '../../', dir);
1917
bench.start();
2018
for (let i = 0; i < n; i++) {
21-
fs.readdirSync(fullPath, { withFileTypes, recursive });
19+
fs.readdirSync(fullPath, { withFileTypes });
2220
}
2321
bench.end(n);
2422
}

‎lib/fs.js‎

Lines changed: 47 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ const {
2828
ArrayFromAsync,
2929
ArrayPrototypePush,
3030
BigIntPrototypeToString,
31-
Boolean,
3231
FunctionPrototypeCall,
3332
MathMax,
3433
Number,
@@ -57,9 +56,6 @@ const {
5756
F_OK,
5857
O_WRONLY,
5958
O_SYMLINK,
60-
UV_DIRENT_DIR,
61-
UV_DIRENT_LINK,
62-
UV_DIRENT_UNKNOWN,
6359
} = constants;
6460

6561
const pathModule = require('path');
@@ -103,10 +99,11 @@ const {
10399
kReadFileBufferLength,
104100
kMaxUserId,
105101
},
102+
collectRecursiveReaddirResult,
106103
copyObject,
107104
Dirent,
108-
getDirent,
109105
getDirents,
106+
getRecursiveDirents,
110107
getOptions,
111108
getValidatedFd,
112109
getValidatedPath,
@@ -1743,57 +1740,40 @@ function mkdirSync(path, options) {
17431740
}
17441741

17451742
/**
1746-
* Appends one directory's entries to `context.results` and the subdirectories
1747-
* still to visit to `context.dirs` (with the prefix their entries get in
1748-
* string results in `context.prefixes`). `result` is a `binding.readdir()`
1749-
* result with file types, so only symbolic links and entries of unknown type
1750-
* need a stat() to find out whether they lead to a directory.
1751-
* @param {string} dir
1752-
* @param {string} prefix
1753-
* @param {[string[], number[]]} result
1754-
* @param {{ withFileTypes: boolean, results: (string | Dirent)[], dirs: string[], prefixes: string[] }} context
1755-
*/
1756-
function collectRecursiveReaddirResult(dir, prefix, { 0: names, 1: types }, context) {
1757-
const { length } = names;
1758-
for (let i = 0; i < length; i++) {
1759-
const name = names[i];
1760-
const relative = prefix === '' ? name : `${prefix}${pathModule.sep}${name}`;
1761-
let isDirectory;
1762-
if (context.withFileTypes) {
1763-
const dirent = getDirent(dir, name, types[i]);
1764-
ArrayPrototypePush(context.results, dirent);
1765-
// Follow symbolic links to directories, see https://github.com/nodejs/node/issues/52663
1766-
isDirectory = dirent.isDirectory() ||
1767-
(dirent.isSymbolicLink() && binding.internalModuleStat(pathModule.join(dir, name)) === 1);
1768-
} else {
1769-
ArrayPrototypePush(context.results, relative);
1770-
const type = types[i];
1771-
isDirectory = type === UV_DIRENT_DIR ||
1772-
((type === UV_DIRENT_LINK || type === UV_DIRENT_UNKNOWN) &&
1773-
binding.internalModuleStat(pathModule.join(dir, name)) === 1);
1774-
}
1775-
if (isDirectory) {
1776-
ArrayPrototypePush(context.dirs, pathModule.join(dir, name));
1777-
ArrayPrototypePush(context.prefixes, relative);
1778-
}
1779-
}
1780-
}
1781-
1782-
/*
1783-
* An recursive algorithm for reading the entire contents of the `basePath` directory.
1784-
* This function does not validate `basePath` as a directory. It is passed directly to
1785-
* `binding.readdir`.
1786-
* @param {string} basePath
1743+
* Reads the entire contents of the `basePath` directory. This function does
1744+
* not validate `basePath` as a directory. It is passed directly to
1745+
* `binding.readdirRecursive`, or to `binding.readdir` for each directory when
1746+
* the permission model is enabled, since that checks every directory on the
1747+
* main thread where the native walk can not.
1748+
* @param {string | Buffer} basePath
17871749
* @param {{ encoding: string, withFileTypes: boolean }} options
17881750
* @param {(
17891751
* err?: Error,
17901752
* files?: string[] | Buffer[] | Dirent[]
17911753
* ) => any} callback
17921754
* @returns {void}
1793-
*/
1755+
*/
17941756
function readdirRecursive(basePath, options, callback) {
1757+
if (permission.isEnabled()) {
1758+
readdirRecursiveWithPermissionModel(basePath, options, callback);
1759+
return;
1760+
}
1761+
const withFileTypes = !!options.withFileTypes;
1762+
const req = new FSReqCallback();
1763+
req.oncomplete = (err, result) => {
1764+
if (err) {
1765+
callback(err);
1766+
return;
1767+
}
1768+
callback(null, withFileTypes ? getRecursiveDirents(basePath, result) : result);
1769+
};
1770+
binding.readdirRecursive(basePath, options.encoding, withFileTypes, req);
1771+
}
1772+
1773+
function readdirRecursiveWithPermissionModel(basePath, options, callback) {
1774+
const { encoding } = options;
17951775
const context = {
1796-
withFileTypes: Boolean(options.withFileTypes),
1776+
withFileTypes: !!options.withFileTypes,
17971777
results: [],
17981778
dirs: [basePath],
17991779
prefixes: [''],
@@ -1815,11 +1795,6 @@ function readdirRecursive(basePath, options, callback) {
18151795
return;
18161796
}
18171797

1818-
if (result === undefined) {
1819-
callback(null, context.results);
1820-
return;
1821-
}
1822-
18231798
try {
18241799
collectRecursiveReaddirResult(path, prefix, result, context);
18251800
} catch (err) {
@@ -1834,37 +1809,37 @@ function readdirRecursive(basePath, options, callback) {
18341809
}
18351810
};
18361811

1837-
binding.readdir(path, options.encoding, true, req);
1812+
binding.readdir(path, encoding, true, req);
18381813
}
18391814

18401815
read(context.dirs[i], context.prefixes[i++]);
18411816
}
18421817

18431818
/**
1844-
* An iterative algorithm for reading the entire contents of the `basePath` directory.
1845-
* This function does not validate `basePath` as a directory. It is passed directly to
1846-
* `binding.readdir`.
1847-
* @param {string} basePath
1819+
* Synchronously reads the entire contents of the `basePath` directory, see
1820+
* `readdirRecursive`.
1821+
* @param {string | Buffer} basePath
18481822
* @param {{ encoding: string, withFileTypes: boolean }} options
1849-
* @returns {string[] | Dirent[]}
1823+
* @returns {string[] | Buffer[] | Dirent[]}
18501824
*/
18511825
function readdirSyncRecursive(basePath, options) {
1852-
const context = {
1853-
withFileTypes: Boolean(options.withFileTypes),
1854-
results: [],
1855-
dirs: [basePath],
1856-
prefixes: [''],
1857-
};
1858-
1859-
for (let i = 0; i < context.dirs.length; i++) {
1860-
const dir = context.dirs[i];
1861-
const result = binding.readdir(dir, options.encoding, true);
1862-
if (result !== undefined) {
1826+
const withFileTypes = !!options.withFileTypes;
1827+
if (permission.isEnabled()) {
1828+
const context = {
1829+
withFileTypes,
1830+
results: [],
1831+
dirs: [basePath],
1832+
prefixes: [''],
1833+
};
1834+
for (let i = 0; i < context.dirs.length; i++) {
1835+
const dir = context.dirs[i];
1836+
const result = binding.readdir(dir, options.encoding, true);
18631837
collectRecursiveReaddirResult(dir, context.prefixes[i], result, context);
18641838
}
1839+
return context.results;
18651840
}
1866-
1867-
return context.results;
1841+
const result = binding.readdirRecursive(basePath, options.encoding, withFileTypes);
1842+
return result !== undefined && withFileTypes ? getRecursiveDirents(basePath, result) : result;
18681843
}
18691844

18701845
/**
@@ -1898,9 +1873,6 @@ function readdir(path, options, callback) {
18981873
}
18991874

19001875
if (options.recursive) {
1901-
// Make shallow copy to prevent mutating options from affecting results
1902-
options = copyObject(options);
1903-
19041876
readdirRecursive(path, options, callback);
19051877
return;
19061878
}

‎lib/internal/fs/promises.js‎

Lines changed: 33 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
'use strict';
22

33
const {
4-
ArrayPrototypePop,
54
ArrayPrototypePush,
65
Error,
76
ErrorCaptureStackTrace,
@@ -32,9 +31,6 @@ const {
3231
O_WRONLY,
3332
S_IFMT,
3433
S_IFREG,
35-
UV_DIRENT_DIR,
36-
UV_DIRENT_LINK,
37-
UV_DIRENT_UNKNOWN,
3834
} = constants;
3935

4036
const binding = internalBinding('fs');
@@ -65,9 +61,10 @@ const {
6561
kReadFileUnknownBufferLength,
6662
kWriteFileMaxChunkSize,
6763
},
64+
collectRecursiveReaddirResult,
6865
copyObject,
69-
getDirent,
7066
getDirents,
67+
getRecursiveDirents,
7168
getOptions,
7269
getStatFsFromBinding,
7370
getStatsFromBinding,
@@ -1648,42 +1645,42 @@ async function mkdir(path, options) {
16481645
}
16491646

16501647
async function readdirRecursive(originalPath, options) {
1648+
if (permission.isEnabled()) {
1649+
return readdirRecursiveWithPermissionModel(originalPath, options);
1650+
}
16511651
const withFileTypes = !!options.withFileTypes;
1652-
const readdirWithTypes = (path) => PromisePrototypeThen(
1653-
binding.readdir(path, options.encoding, true, kUsePromises),
1652+
const result = await PromisePrototypeThen(
1653+
binding.readdirRecursive(
1654+
originalPath,
1655+
options.encoding,
1656+
withFileTypes,
1657+
kUsePromises,
1658+
),
16541659
undefined,
16551660
handleErrorFromBinding,
16561661
);
1657-
const result = [];
1658-
const queue = [[originalPath, '', await readdirWithTypes(originalPath)]];
1659-
1660-
while (queue.length > 0) {
1661-
// If we want to implement BFS make this a `shift` call instead of `pop`
1662-
const { 0: path, 1: prefix, 2: { 0: names, 1: types } } = ArrayPrototypePop(queue);
1663-
for (let i = 0; i < names.length; i++) {
1664-
const name = names[i];
1665-
const relative = prefix === '' ? name : `${prefix}${pathModule.sep}${name}`;
1666-
let isDirectory;
1667-
if (withFileTypes) {
1668-
const dirent = getDirent(path, name, types[i]);
1669-
ArrayPrototypePush(result, dirent);
1670-
isDirectory = dirent.isDirectory();
1671-
} else {
1672-
ArrayPrototypePush(result, relative);
1673-
// Entries that are, or may be, symbolic links to directories are followed.
1674-
const type = types[i];
1675-
isDirectory = type === UV_DIRENT_DIR ||
1676-
((type === UV_DIRENT_LINK || type === UV_DIRENT_UNKNOWN) &&
1677-
binding.internalModuleStat(pathModule.join(path, name)) === 1);
1678-
}
1679-
if (isDirectory) {
1680-
const direntPath = pathModule.join(path, name);
1681-
ArrayPrototypePush(queue, [direntPath, relative, await readdirWithTypes(direntPath)]);
1682-
}
1683-
}
1684-
}
1662+
return withFileTypes ? getRecursiveDirents(originalPath, result) : result;
1663+
}
16851664

1686-
return result;
1665+
// TODO: native?
1666+
async function readdirRecursiveWithPermissionModel(basePath, options) {
1667+
const { encoding } = options;
1668+
const context = {
1669+
withFileTypes: !!options.withFileTypes,
1670+
results: [],
1671+
dirs: [basePath],
1672+
prefixes: [''],
1673+
};
1674+
for (let i = 0; i < context.dirs.length; i++) {
1675+
const dir = context.dirs[i];
1676+
const result = await PromisePrototypeThen(
1677+
binding.readdir(dir, encoding, true, kUsePromises),
1678+
undefined,
1679+
handleErrorFromBinding,
1680+
);
1681+
collectRecursiveReaddirResult(dir, context.prefixes[i], result, context);
1682+
}
1683+
return context.results;
16871684
}
16881685

16891686
async function readdir(path, options) {

0 commit comments

Comments
 (0)