fs: add followSymlinks option to glob

PR-URL: https://github.com/nodejs/node/pull/62695
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
This commit is contained in:
Matteo Collina authored and Antoine du Hamel committed 2026-05-07 18:14:57 +02:00
1 parent dafed453b2
commit 4a506acd16
3 files changed
+308 -28

No files matched your search

+24
View File
@@ -1088,6 +1088,9 @@ behavior is similar to `cp dir1/ dir2/`.
<!-- YAML
added: v22.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/62695
description: Add support for the `followSymlinks` option.
- version: v24.1.0
pr-url: https://github.com/nodejs/node/pull/58182
description: Add support for `URL` instances for `cwd` option.
@@ -1113,11 +1116,16 @@ changes:
If a string array is provided, each string should be a glob pattern that
specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are
not supported.
* `followSymlinks` {boolean} When `true`, symbolic links to directories are
followed while expanding `**` patterns. **Default:** `false`.
* `withFileTypes` {boolean} `true` if the glob should return paths as Dirents,
`false` otherwise. **Default:** `false`.
* Returns: {AsyncIterator} An AsyncIterator that yields the paths of files
that match the pattern.
When `followSymlinks` is enabled, detected symbolic link cycles are not
traversed recursively.
```mjs
import { glob } from 'node:fs/promises';
@@ -3194,6 +3202,9 @@ descriptor. See [`fs.utimes()`][].
<!-- YAML
added: v22.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/62695
description: Add support for the `followSymlinks` option.
- version: v24.1.0
pr-url: https://github.com/nodejs/node/pull/58182
description: Add support for `URL` instances for `cwd` option.
@@ -3217,6 +3228,8 @@ changes:
* `exclude` {Function|string\[]} Function to filter out files/directories or a
list of glob patterns to be excluded. If a function is provided, return
`true` to exclude the item, `false` to include it. **Default:** `undefined`.
* `followSymlinks` {boolean} When `true`, symbolic links to directories are
followed while expanding `**` patterns. **Default:** `false`.
* `withFileTypes` {boolean} `true` if the glob should return paths as Dirents,
`false` otherwise. **Default:** `false`.
@@ -3225,6 +3238,9 @@ changes:
* Retrieves the files matching the specified pattern.
When `followSymlinks` is enabled, detected symbolic link cycles are not
traversed recursively.
```mjs
import { glob } from 'node:fs';
@@ -5763,6 +5779,9 @@ Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
<!-- YAML
added: v22.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/62695
description: Add support for the `followSymlinks` option.
- version: v24.1.0
pr-url: https://github.com/nodejs/node/pull/58182
description: Add support for `URL` instances for `cwd` option.
@@ -5785,10 +5804,15 @@ changes:
* `exclude` {Function|string\[]} Function to filter out files/directories or a
list of glob patterns to be excluded. If a function is provided, return
`true` to exclude the item, `false` to include it. **Default:** `undefined`.
* `followSymlinks` {boolean} When `true`, symbolic links to directories are
followed while expanding `**` patterns. **Default:** `false`.
* `withFileTypes` {boolean} `true` if the glob should return paths as Dirents,
`false` otherwise. **Default:** `false`.
* Returns: {string\[]} paths of files that match the pattern.
When `followSymlinks` is enabled, detected symbolic link cycles are not
traversed recursively.
```mjs
import { globSync } from 'node:fs';
+176 -28
View File
@@ -16,8 +16,18 @@ const {
StringPrototypeEndsWith,
} = primordials;
const { lstatSync, readdirSync } = require('fs');
const { lstat, readdir } = require('fs/promises');
const {
lstatSync,
readdirSync,
realpathSync,
statSync,
} = require('fs');
const {
lstat,
readdir,
realpath,
stat,
} = require('fs/promises');
const { join, resolve, basename, isAbsolute, dirname } = require('path');
const {
@@ -26,6 +36,7 @@ const {
isMacOS,
} = require('internal/util');
const {
validateBoolean,
validateObject,
validateString,
validateStringArray,
@@ -113,10 +124,20 @@ function createMatcher(pattern, options = kEmptyObject) {
return new (lazyMinimatch().Minimatch)(pattern, opts);
}
function cloneSet(values) {
const cloned = new SafeSet();
for (const value of values) {
cloned.add(value);
}
return cloned;
}
class Cache {
#cache = new SafeMap();
#statsCache = new SafeMap();
#followStatsCache = new SafeMap();
#readdirCache = new SafeMap();
#realpathCache = new SafeMap();
stat(path) {
const cached = this.#statsCache.get(path);
@@ -137,6 +158,52 @@ class Cache {
this.#statsCache.set(path, val);
return val;
}
followStat(path) {
const cached = this.#followStatsCache.get(path);
if (cached) {
return cached;
}
const promise = PromisePrototypeThen(stat(path), null, () => null);
this.#followStatsCache.set(path, promise);
return promise;
}
followStatSync(path) {
const cached = this.#followStatsCache.get(path);
if (cached && !(cached instanceof Promise)) {
return cached;
}
let val;
try {
val = statSync(path);
} catch {
val = null;
}
this.#followStatsCache.set(path, val);
return val;
}
realpath(path) {
const cached = this.#realpathCache.get(path);
if (cached) {
return cached;
}
const promise = PromisePrototypeThen(realpath(path), null, () => null);
this.#realpathCache.set(path, promise);
return promise;
}
realpathSync(path) {
const cached = this.#realpathCache.get(path);
if (cached && !(cached instanceof Promise)) {
return cached;
}
let val;
try {
val = realpathSync(path);
} catch {
val = null;
}
this.#realpathCache.set(path, val);
return val;
}
addToStatCache(path, val) {
this.#statsCache.set(path, val);
}
@@ -183,13 +250,15 @@ class Pattern {
#globStrings;
indexes;
symlinks;
realpaths;
last;
constructor(pattern, globStrings, indexes, symlinks) {
constructor(pattern, globStrings, indexes, symlinks, realpaths = new SafeSet()) {
this.#pattern = pattern;
this.#globStrings = globStrings;
this.indexes = indexes;
this.symlinks = symlinks;
this.realpaths = realpaths;
this.last = pattern.length - 1;
}
@@ -207,8 +276,8 @@ class Pattern {
at(index) {
return ArrayPrototypeAt(this.#pattern, index);
}
child(indexes, symlinks = new SafeSet()) {
return new Pattern(this.#pattern, this.#globStrings, indexes, symlinks);
child(indexes, symlinks = new SafeSet(), realpaths = this.realpaths) {
return new Pattern(this.#pattern, this.#globStrings, indexes, symlinks, realpaths);
}
test(index, path) {
if (index > this.#pattern.length) {
@@ -266,11 +335,16 @@ class Glob {
#subpatterns = new SafeMap();
#patterns;
#withFileTypes;
#followSymlinks = false;
#isExcluded = () => false;
constructor(pattern, options = kEmptyObject) {
validateObject(options, 'options');
const { exclude, cwd, withFileTypes } = options;
const { exclude, cwd, followSymlinks, withFileTypes } = options;
this.#root = toPathIfFileURL(cwd) ?? '.';
if (followSymlinks != null) {
validateBoolean(followSymlinks, 'options.followSymlinks');
this.#followSymlinks = followSymlinks;
}
this.#withFileTypes = !!withFileTypes;
if (exclude != null) {
validateStringArrayOrFunction(exclude, 'options.exclude');
@@ -326,6 +400,68 @@ class Glob {
) : undefined,
);
}
#isDirectorySync(path, stat, pattern) {
if (stat?.isDirectory()) {
return true;
}
if (!stat?.isSymbolicLink()) {
return false;
}
if (this.#followSymlinks) {
return !!this.#cache.followStatSync(path)?.isDirectory();
}
return pattern.hasSeenSymlinks;
}
async #isDirectory(path, stat, pattern) {
if (stat?.isDirectory()) {
return true;
}
if (!stat?.isSymbolicLink()) {
return false;
}
if (this.#followSymlinks) {
return !!(await this.#cache.followStat(path))?.isDirectory();
}
return pattern.hasSeenSymlinks;
}
#nextRealpathsSync(path, isDirectory, pattern) {
if (!this.#followSymlinks || !isDirectory) {
return pattern.realpaths;
}
const real = this.#cache.realpathSync(path);
if (real === null) {
return pattern.realpaths;
}
const realpaths = cloneSet(pattern.realpaths);
realpaths.add(real);
return realpaths;
}
async #nextRealpaths(path, isDirectory, pattern) {
if (!this.#followSymlinks || !isDirectory) {
return pattern.realpaths;
}
const real = await this.#cache.realpath(path);
if (real === null) {
return pattern.realpaths;
}
const realpaths = cloneSet(pattern.realpaths);
realpaths.add(real);
return realpaths;
}
async #isCyclic(path, isDirectory, pattern) {
if (!this.#followSymlinks || !isDirectory) {
return false;
}
const real = await this.#cache.realpath(path);
return real !== null && pattern.realpaths.has(real);
}
#isCyclicSync(path, isDirectory, pattern) {
if (!this.#followSymlinks || !isDirectory) {
return false;
}
const real = this.#cache.realpathSync(path);
return real !== null && pattern.realpaths.has(real);
}
#addSubpattern(path, pattern) {
if (this.#isExcluded(path)) {
return;
@@ -363,7 +499,7 @@ class Glob {
const fullpath = resolve(this.#root, path);
const stat = this.#cache.statSync(fullpath);
const last = pattern.last;
const isDirectory = stat?.isDirectory() || (stat?.isSymbolicLink() && pattern.hasSeenSymlinks);
const isDirectory = this.#isDirectorySync(fullpath, stat, pattern);
const isLast = pattern.isLast(isDirectory);
const isFirst = pattern.isFirst();
@@ -408,10 +544,12 @@ class Glob {
this.#results.add(path);
}
if (!isDirectory) {
if (!isDirectory || this.#isCyclicSync(fullpath, isDirectory, pattern)) {
return;
}
const nextRealpaths = this.#nextRealpathsSync(fullpath, isDirectory, pattern);
let children;
const firstPattern = pattern.indexes.size === 1 && pattern.at(pattern.indexes.values().next().value);
if (typeof firstPattern === 'string') {
@@ -429,7 +567,10 @@ class Glob {
for (let i = 0; i < children.length; i++) {
const entry = children[i];
const entryPath = join(path, entry.name);
this.#cache.addToStatCache(join(fullpath, entry.name), entry);
const entryFullpath = join(fullpath, entry.name);
this.#cache.addToStatCache(entryFullpath, entry);
const entryIsDirectory = entry.isDirectory() ||
(this.#followSymlinks && entry.isSymbolicLink() && !!this.#cache.followStatSync(entryFullpath)?.isDirectory());
const subPatterns = new SafeSet();
const nSymlinks = new SafeSet();
@@ -441,7 +582,7 @@ class Glob {
const current = pattern.at(index);
const nextIndex = index + 1;
const next = pattern.at(nextIndex);
const fromSymlink = pattern.symlinks.has(index);
const fromSymlink = !this.#followSymlinks && pattern.symlinks.has(index);
if (current === lazyMinimatch().GLOBSTAR) {
const isDot = entry.name[0] === '.';
@@ -458,7 +599,7 @@ class Glob {
(this.#exclude && this.#exclude(this.#withFileTypes ? entry : entry.name))) {
continue;
}
if (!fromSymlink && entry.isDirectory()) {
if (!fromSymlink && entryIsDirectory) {
// If directory, add ** to its potential patterns
subPatterns.add(index);
} else if (!fromSymlink && index === last) {
@@ -471,24 +612,24 @@ class Glob {
if (nextMatches && nextIndex === last && !isLast) {
// If next pattern is the last one, add to results
this.#results.add(entryPath);
} else if (nextMatches && entry.isDirectory()) {
} else if (nextMatches && entryIsDirectory) {
// Pattern matched, meaning two patterns forward
// are also potential patterns
// e.g **/b/c when entry is a/b - add c to potential patterns
subPatterns.add(index + 2);
}
if ((nextMatches || pattern.at(0) === '.') &&
(entry.isDirectory() || entry.isSymbolicLink()) && !fromSymlink) {
(entryIsDirectory || entry.isSymbolicLink()) && !fromSymlink) {
// If pattern after ** matches, or pattern starts with "."
// and entry is a directory or symlink, add to potential patterns
subPatterns.add(nextIndex);
}
if (entry.isSymbolicLink()) {
if (!this.#followSymlinks && entry.isSymbolicLink()) {
nSymlinks.add(index);
}
if (next === '..' && entry.isDirectory()) {
if (next === '..' && entryIsDirectory) {
// In case pattern is "**/..",
// both parent and current directory should be added to the queue
// if this is the last pattern, add to results instead
@@ -531,14 +672,14 @@ class Glob {
// add next pattern to potential patterns, or to results if it's the last pattern
if (index === last) {
this.#results.add(entryPath);
} else if (entry.isDirectory()) {
} else if (entryIsDirectory) {
subPatterns.add(nextIndex);
}
}
}
if (subPatterns.size > 0) {
// If there are potential patterns, add to queue
this.#addSubpattern(entryPath, pattern.child(subPatterns, nSymlinks));
this.#addSubpattern(entryPath, pattern.child(subPatterns, nSymlinks, nextRealpaths));
}
}
}
@@ -564,7 +705,7 @@ class Glob {
const fullpath = resolve(this.#root, path);
const stat = await this.#cache.stat(fullpath);
const last = pattern.last;
const isDirectory = stat?.isDirectory() || (stat?.isSymbolicLink() && pattern.hasSeenSymlinks);
const isDirectory = await this.#isDirectory(fullpath, stat, pattern);
const isLast = pattern.isLast(isDirectory);
const isFirst = pattern.isFirst();
@@ -618,10 +759,12 @@ class Glob {
}
}
if (!isDirectory) {
if (!isDirectory || await this.#isCyclic(fullpath, isDirectory, pattern)) {
return;
}
const nextRealpaths = await this.#nextRealpaths(fullpath, isDirectory, pattern);
let children;
const firstPattern = pattern.indexes.size === 1 && pattern.at(pattern.indexes.values().next().value);
if (typeof firstPattern === 'string') {
@@ -639,7 +782,12 @@ class Glob {
for (let i = 0; i < children.length; i++) {
const entry = children[i];
const entryPath = join(path, entry.name);
this.#cache.addToStatCache(join(fullpath, entry.name), entry);
const entryFullpath = join(fullpath, entry.name);
this.#cache.addToStatCache(entryFullpath, entry);
const entryIsDirectory = entry.isDirectory() ||
(this.#followSymlinks &&
entry.isSymbolicLink() &&
!!(await this.#cache.followStat(entryFullpath))?.isDirectory());
const subPatterns = new SafeSet();
const nSymlinks = new SafeSet();
@@ -651,7 +799,7 @@ class Glob {
const current = pattern.at(index);
const nextIndex = index + 1;
const next = pattern.at(nextIndex);
const fromSymlink = pattern.symlinks.has(index);
const fromSymlink = !this.#followSymlinks && pattern.symlinks.has(index);
if (current === lazyMinimatch().GLOBSTAR) {
const isDot = entry.name[0] === '.';
@@ -668,7 +816,7 @@ class Glob {
(this.#exclude && this.#exclude(this.#withFileTypes ? entry : entry.name))) {
continue;
}
if (!fromSymlink && entry.isDirectory()) {
if (!fromSymlink && entryIsDirectory) {
// If directory, add ** to its potential patterns
subPatterns.add(index);
} else if (!fromSymlink && index === last) {
@@ -685,24 +833,24 @@ class Glob {
if (!this.#results.has(entryPath) && this.#results.add(entryPath)) {
yield this.#withFileTypes ? entry : entryPath;
}
} else if (nextMatches && entry.isDirectory()) {
} else if (nextMatches && entryIsDirectory) {
// Pattern matched, meaning two patterns forward
// are also potential patterns
// e.g **/b/c when entry is a/b - add c to potential patterns
subPatterns.add(index + 2);
}
if ((nextMatches || pattern.at(0) === '.') &&
(entry.isDirectory() || entry.isSymbolicLink()) && !fromSymlink) {
(entryIsDirectory || entry.isSymbolicLink()) && !fromSymlink) {
// If pattern after ** matches, or pattern starts with "."
// and entry is a directory or symlink, add to potential patterns
subPatterns.add(nextIndex);
}
if (entry.isSymbolicLink()) {
if (!this.#followSymlinks && entry.isSymbolicLink()) {
nSymlinks.add(index);
}
if (next === '..' && entry.isDirectory()) {
if (next === '..' && entryIsDirectory) {
// In case pattern is "**/..",
// both parent and current directory should be added to the queue
// if this is the last pattern, add to results instead
@@ -761,14 +909,14 @@ class Glob {
yield this.#withFileTypes ? entry : entryPath;
}
}
} else if (entry.isDirectory()) {
} else if (entryIsDirectory) {
subPatterns.add(nextIndex);
}
}
}
if (subPatterns.size > 0) {
// If there are potential patterns, add to queue
this.#addSubpattern(entryPath, pattern.child(subPatterns, nSymlinks));
this.#addSubpattern(entryPath, pattern.child(subPatterns, nSymlinks, nextRealpaths));
}
}
}
+108
View File
@@ -36,6 +36,9 @@ async function setup() {
const symlinkTo = resolve(fixtureDir, 'a/symlink/a/b/c');
const symlinkFrom = '../..';
const followTarget = resolve(fixtureDir, 'follow/target');
const followLink = resolve(fixtureDir, 'follow/link');
const followCycle = resolve(fixtureDir, 'follow/cycle');
for (const file of files) {
const f = resolve(fixtureDir, file);
@@ -44,12 +47,19 @@ async function setup() {
await writeFile(f, 'i like tests');
}
await mkdir(followTarget, { recursive: true });
await writeFile(resolve(followTarget, 'file.txt'), 'follow symlinks');
if (!common.isWindows) {
const d = dirname(symlinkTo);
await mkdir(d, { recursive: true });
await symlink(symlinkFrom, symlinkTo, 'dir');
}
const linkType = common.isWindows ? 'junction' : 'dir';
await symlink(followTarget, followLink, linkType);
await symlink(resolve(fixtureDir, 'follow'), followCycle, linkType);
await Promise.all(['foo', 'bar', 'baz', 'asdf', 'quux', 'qwer', 'rewq'].map(async function(w) {
await mkdir(resolve(absDir, w), { recursive: true });
}));
@@ -216,6 +226,9 @@ const patterns = {
common.isWindows ? null : 'a/symlink',
'a/x',
'a/z',
'follow/cycle',
'follow/link',
'follow/target',
],
[`{${absDir}/*,*}`]: [
`${absDir}/asdf`,
@@ -226,6 +239,7 @@ const patterns = {
`${absDir}/qwer`,
`${absDir}/rewq`,
'a',
'follow',
],
'a/!(symlink)/**': [
'a/abcdef',
@@ -524,6 +538,100 @@ describe('fsPromises glob - exclude', function() {
}
});
const followSymlinkPattern = 'follow/**';
const followSymlinkExpected = [
'follow',
'follow/cycle',
'follow/link',
'follow/target',
'follow/target/file.txt',
].map((item) => item.replaceAll('/', sep)).sort();
const followSymlinkExpectedWithFollow = [
...followSymlinkExpected,
'follow/link/file.txt'.replaceAll('/', sep),
].sort();
const getNestedCycleMatches = (matches) => {
return matches.filter((match) => match.startsWith(`follow${sep}cycle${sep}`));
};
describe('glob - followSymlinks', function() {
const promisified = promisify(glob);
test('does not follow symlinks by default', async () => {
const actual = (await promisified(followSymlinkPattern, { cwd: fixtureDir })).sort();
assert.deepStrictEqual(actual, followSymlinkExpected);
});
test('follows symlinked directories when enabled', async () => {
const actual = (await promisified(followSymlinkPattern, {
cwd: fixtureDir,
followSymlinks: true,
})).sort();
assert.deepStrictEqual(actual, followSymlinkExpectedWithFollow);
assert.deepStrictEqual(getNestedCycleMatches(actual), []);
});
});
describe('globSync - followSymlinks', function() {
test('does not follow symlinks by default', () => {
const actual = globSync(followSymlinkPattern, { cwd: fixtureDir }).sort();
assert.deepStrictEqual(actual, followSymlinkExpected);
});
test('validates followSymlinks', () => {
assert.throws(() => {
globSync(followSymlinkPattern, {
cwd: fixtureDir,
followSymlinks: 1,
});
}, {
code: 'ERR_INVALID_ARG_TYPE',
});
});
test('follows symlinked directories when enabled', () => {
const actual = globSync(followSymlinkPattern, {
cwd: fixtureDir,
followSymlinks: true,
}).sort();
assert.deepStrictEqual(actual, followSymlinkExpectedWithFollow);
assert.deepStrictEqual(getNestedCycleMatches(actual), []);
});
test('supports withFileTypes when following symlinked directories', () => {
const actual = globSync(followSymlinkPattern, {
cwd: fixtureDir,
followSymlinks: true,
withFileTypes: true,
});
assertDirents(actual);
const normalized = actual.map(normalizeDirent).sort();
assert.deepStrictEqual(normalized, followSymlinkExpectedWithFollow);
assert.deepStrictEqual(getNestedCycleMatches(normalized), []);
});
});
describe('fsPromises glob - followSymlinks', function() {
test('does not follow symlinks by default', async () => {
const actual = [];
for await (const item of asyncGlob(followSymlinkPattern, { cwd: fixtureDir })) actual.push(item);
actual.sort();
assert.deepStrictEqual(actual, followSymlinkExpected);
});
test('follows symlinked directories when enabled', async () => {
const actual = [];
for await (const item of asyncGlob(followSymlinkPattern, {
cwd: fixtureDir,
followSymlinks: true,
})) actual.push(item);
actual.sort();
assert.deepStrictEqual(actual, followSymlinkExpectedWithFollow);
assert.deepStrictEqual(getNestedCycleMatches(actual), []);
});
});
describe('glob - with restricted directory', function() {
test('*', async () => {
const restrictedDir = tmpdir.resolve('restricted');