Skip to content

fs: add skipSymlinkDir option to skip symbolic dirs for fs.readdir #52553

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

Closed
wants to merge 1 commit into from
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -1368,6 +1368,9 @@ closed after the iterator exits.
<!-- YAML
added: v10.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/52553
description: New option `skipSymlinkDir` was added.
- version:
- v20.1.0
- v18.17.0
Expand All @@ -1385,6 +1388,9 @@ changes:
* `recursive` {boolean} If `true`, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files, and
directories. **Default:** `false`.
* `skipSymlinkDir` {boolean} This option is only effective when `recursive`
is set to `true`. If `true`, symbolic link directories are skipped. If
`false`, symbolic link directories are included. **Default:** `false`.
* Returns: {Promise} Fulfills with an array of the names of the files in
the directory excluding `'.'` and `'..'`.

Expand Down Expand Up @@ -3728,6 +3734,9 @@ above values.
<!-- YAML
added: v0.1.8
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/52553
description: New option `skipSymlinkDir` was added.
- version:
- v20.1.0
- v18.17.0
Expand Down Expand Up @@ -3765,6 +3774,9 @@ changes:
* `recursive` {boolean} If `true`, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files and
directories. **Default:** `false`.
* `skipSymlinkDir` {boolean} This option is only effective when `recursive`
is set to `true`. If `true`, symbolic link directories are skipped. If
`false`, symbolic link directories are included. **Default:** `false`.
* `callback` {Function}
* `err` {Error}
* `files` {string\[]|Buffer\[]|fs.Dirent\[]}
Expand Down Expand Up @@ -5857,6 +5869,9 @@ this API: [`fs.open()`][].
<!-- YAML
added: v0.1.21
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/52553
description: New option `skipSymlinkDir` was added.
- version:
- v20.1.0
- v18.17.0
Expand All @@ -5878,6 +5893,9 @@ changes:
* `recursive` {boolean} If `true`, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files, and
directories. **Default:** `false`.
* `skipSymlinkDir` {boolean} This option is only effective when `recursive`
is set to `true`. If `true`, symbolic link directories are skipped. If
`false`, symbolic link directories are included. **Default:** `false`.
* Returns: {string\[]|Buffer\[]|fs.Dirent\[]}

Reads the contents of the directory.
Expand Down
30 changes: 25 additions & 5 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1389,13 +1389,19 @@ function mkdirSync(path, options) {
function readdirSyncRecursive(basePath, options) {
const withFileTypes = Boolean(options.withFileTypes);
const encoding = options.encoding;

const skipSymlinkDir = options.skipSymlinkDir || false;
const readdirResults = [];
const pathsQueue = [basePath];

function read(path) {
const namespacePath = pathModule.toNamespacedPath(path);
if (skipSymlinkDir) {
if (lstatSync(namespacePath).isSymbolicLink()) {
return;
}
}
const readdirResult = binding.readdir(
pathModule.toNamespacedPath(path),
namespacePath,
encoding,
withFileTypes,
);
Expand All @@ -1413,16 +1419,28 @@ function readdirSyncRecursive(basePath, options) {
for (let i = 0; i < length; i++) {
const dirent = getDirent(path, readdirResult[0][i], readdirResult[1][i]);
ArrayPrototypePush(readdirResults, dirent);
if (dirent.isDirectory()) {
if (skipSymlinkDir) {
if (dirent.isSymbolicLink()) {
continue;
}
}
const resultPath = pathModule.join(path, dirent.name);
const stat = binding.internalModuleStat(resultPath);
if (stat === 1) {
ArrayPrototypePush(pathsQueue, pathModule.join(dirent.parentPath, dirent.name));
}
}
} else {
for (let i = 0; i < readdirResult.length; i++) {
const resultPath = pathModule.join(path, readdirResult[i]);
const relativeResultPath = pathModule.relative(basePath, resultPath);
const stat = binding.internalModuleStat(resultPath);
ArrayPrototypePush(readdirResults, relativeResultPath);
if (skipSymlinkDir) {
if (lstatSync(resultPath).isSymbolicLink()) {
continue;
}
}
const stat = binding.internalModuleStat(resultPath);
// 1 indicates directory
if (stat === 1) {
ArrayPrototypePush(pathsQueue, resultPath);
Expand Down Expand Up @@ -1497,7 +1515,9 @@ function readdirSync(path, options) {
if (options.recursive != null) {
validateBoolean(options.recursive, 'options.recursive');
}

if (options.skipSymlinkDir != null) {
validateBoolean(options.skipSymlinkDir, 'options.skipSymlinkDir');
}
if (options.recursive) {
return readdirSyncRecursive(path, options);
}
Expand Down
23 changes: 22 additions & 1 deletion lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,14 @@ async function mkdir(path, options) {

async function readdirRecursive(originalPath, options) {
const result = [];
const skipSymlinkDir = options.skipSymlinkDir || false;

if (skipSymlinkDir) {
const stats = await lstat(originalPath);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm no CPP expert, but benchmark-wise, wouldn't this call make us get the file twice? Is there a CPP way to achieve this same result?

Disclaimer: I'm not a CPP expert (or even a novice)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't find an effective way to acquire stat in cpp way directly to avoid this dilemma, it would be great if anyone could help, and this will only affect efficiency when using skipSymlinkDir to skip symbolic link dirs.

if (stats.isSymbolicLink()) {
return result;
}
}
const queue = [
[
originalPath,
Expand All @@ -890,8 +898,15 @@ async function readdirRecursive(originalPath, options) {
// If we want to implement BFS make this a `shift` call instead of `pop`
const { 0: path, 1: readdir } = ArrayPrototypePop(queue);
for (const dirent of getDirents(path, readdir)) {
if (skipSymlinkDir) {
if (dirent.isSymbolicLink()) {
continue;
}
}
ArrayPrototypePush(result, dirent);
if (dirent.isDirectory()) {
const direntPath = pathModule.join(path, dirent.name);
const stat = binding.internalModuleStat(direntPath);
if (stat === 1) {
const direntPath = pathModule.join(path, dirent.name);
ArrayPrototypePush(queue, [
direntPath,
Expand Down Expand Up @@ -919,6 +934,12 @@ async function readdirRecursive(originalPath, options) {
result,
pathModule.relative(originalPath, direntPath),
);
if (skipSymlinkDir) {
const stats = await lstat(direntPath);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See previous comment

if (stats.isSymbolicLink()) {
continue;
}
}
if (stat === 1) {
ArrayPrototypePush(queue, [
direntPath,
Expand Down
63 changes: 57 additions & 6 deletions test/sequential/test-fs-readdir-recursive.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,10 @@ const symlinksRootPath = pathModule.join(readdirDir, 'symlinks');
const symlinkTargetFile = pathModule.join(symlinksRootPath, 'symlink-target-file');
const symlinkTargetDir = pathModule.join(symlinksRootPath, 'symlink-target-dir');
fs.mkdirSync(symlinksRootPath);
fs.symlinkSync(symlinksRootPath, pathModule.join(readdirDir, 'symlinks-src'));
fs.writeFileSync(symlinkTargetFile, '');
fs.mkdirSync(symlinkTargetDir);
fs.writeFileSync(pathModule.join(symlinkTargetDir, 'symlink-target-dir-file'), '');
fs.symlinkSync(symlinkTargetFile, pathModule.join(symlinksRootPath, 'symlink-src-file'));
fs.symlinkSync(symlinkTargetDir, pathModule.join(symlinksRootPath, 'symlink-src-dir'));

Expand All @@ -110,8 +112,19 @@ const expected = [
'q', 'q/bar', 'q/foo', 'qq', 'qq/bar', 'qq/foo',
'r', 'r/bar', 'r/foo', 'rr', 'rr/bar', 'rr/foo',
's', 's/bar', 's/foo', 'ss', 'ss/bar', 'ss/foo',
'symlinks', 'symlinks/symlink-src-dir', 'symlinks/symlink-src-file',
'symlinks/symlink-target-dir', 'symlinks/symlink-target-file',
'symlinks', 'symlinks-src',
'symlinks-src/symlink-src-dir',
'symlinks-src/symlink-src-dir/symlink-target-dir-file',
'symlinks-src/symlink-src-file',
'symlinks-src/symlink-target-dir',
'symlinks-src/symlink-target-dir/symlink-target-dir-file',
'symlinks-src/symlink-target-file',
'symlinks/symlink-src-dir',
'symlinks/symlink-src-dir/symlink-target-dir-file',
'symlinks/symlink-src-file',
'symlinks/symlink-target-dir',
'symlinks/symlink-target-dir/symlink-target-dir-file',
'symlinks/symlink-target-file',
't', 't/bar', 't/foo', 'tt', 'tt/bar', 'tt/foo',
'u', 'u/bar', 'u/foo', 'uu', 'uu/bar', 'uu/foo',
'v', 'v/bar', 'v/foo', 'vv', 'vv/bar', 'vv/foo',
Expand All @@ -121,16 +134,30 @@ const expected = [
'z', 'z/bar', 'z/foo', 'zz', 'zz/bar', 'zz/foo',
];

const symlinkFiles = [
'symlinks-src/symlink-src-dir',
'symlinks-src/symlink-src-dir/symlink-target-dir-file',
'symlinks-src/symlink-src-file',
'symlinks-src/symlink-target-dir',
'symlinks-src/symlink-target-dir/symlink-target-dir-file',
'symlinks-src/symlink-target-file',
'symlinks/symlink-src-dir/symlink-target-dir-file',
];
const skipSymlinkExpected = expected.filter((file) => !symlinkFiles.includes(file));

// Normalize paths once for non POSIX platforms
for (let i = 0; i < expected.length; i++) {
expected[i] = pathModule.normalize(expected[i]);
}
for (let i = 0; i < symlinkFiles.length; i++) {
symlinkFiles[i] = pathModule.normalize(symlinkFiles[i]);
}

function getDirentPath(dirent) {
return pathModule.relative(readdirDir, pathModule.join(dirent.path, dirent.name));
}

function assertDirents(dirents) {
function assertDirents(dirents, expected) {
assert.strictEqual(dirents.length, expected.length);
dirents.sort((a, b) => (getDirentPath(a) < getDirentPath(b) ? -1 : 1));
assert.deepStrictEqual(
Expand All @@ -154,7 +181,13 @@ function assertDirents(dirents) {
// readdirSync { recursive, withFileTypes }
{
const result = fs.readdirSync(readdirDir, { recursive: true, withFileTypes: true });
assertDirents(result);
assertDirents(result, expected);
}

// readdirSync { recursive, skipSymlinkDir }
{
const result = fs.readdirSync(readdirDir, { recursive: true, skipSymlinkDir: true });
assert.deepStrictEqual(result.sort(), skipSymlinkExpected);
}

// readdir
Expand All @@ -171,7 +204,15 @@ function assertDirents(dirents) {
{
fs.readdir(readdirDir, { recursive: true, withFileTypes: true },
common.mustSucceed((result) => {
assertDirents(result);
assertDirents(result, expected);
}));
}

// Readdir { recursive, skipSymlinkDir } callback
{
fs.readdir(readdirDir, { recursive: true, skipSymlinkDir: true },
common.mustSucceed((result) => {
assert.deepStrictEqual(result.sort(), skipSymlinkExpected);
}));
}

Expand All @@ -191,7 +232,17 @@ function assertDirents(dirents) {
{
async function test() {
const result = await fs.promises.readdir(readdirDir, { recursive: true, withFileTypes: true });
assertDirents(result);
assertDirents(result, expected);
}

test().then(common.mustCall());
}

// fs.promises.readdir { recursive, skipSymlinkDir }
{
async function test() {
const result = await fs.promises.readdir(readdirDir, { recursive: true, skipSymlinkDir: true });
assert.deepStrictEqual(result.sort(), skipSymlinkExpected);
}

test().then(common.mustCall());
Expand Down