Skip to content

Commit ec4c561

Browse files
committed
path: add path.glob and path.globToRegExp
1 parent 37d1fe8 commit ec4c561

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

lib/path.js

+28
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ const {
4747
validateString,
4848
} = require('internal/validators');
4949

50+
51+
let minimatch;
52+
function lazyMinimatch() {
53+
minimatch ??= require('internal/deps/minimatch/index');
54+
return minimatch;
55+
}
56+
5057
const platformIsWin32 = (process.platform === 'win32');
5158

5259
function isPathSeparator(code) {
@@ -153,6 +160,23 @@ function _format(sep, pathObject) {
153160
return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`;
154161
}
155162

163+
164+
/**
165+
* @param {string} path
166+
* @returns {Function}
167+
*/
168+
function glob(pattern) {
169+
return lazyMinimatch().filter(pattern);
170+
}
171+
172+
/**
173+
* @param {string} path
174+
* @returns {RegExp}
175+
*/
176+
function globToRegExp(pattern) {
177+
return lazyMinimatch().makeRe(pattern);
178+
}
179+
156180
const win32 = {
157181
/**
158182
* path.resolve([from ...], to)
@@ -1064,6 +1088,8 @@ const win32 = {
10641088

10651089
return ret;
10661090
},
1091+
glob,
1092+
globToRegExp,
10671093

10681094
sep: '\\',
10691095
delimiter: ';',
@@ -1530,6 +1556,8 @@ const posix = {
15301556

15311557
return ret;
15321558
},
1559+
glob,
1560+
globToRegExp,
15331561

15341562
sep: '/',
15351563
delimiter: ':',

test/parallel/test-path-glob.mjs

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { describe, it } from 'node:test';
2+
import * as assert from 'node:assert';
3+
import * as path from 'node:path';
4+
5+
describe('path.glob', () => {
6+
it('should return a filter function', () => {
7+
const fn = path.glob('*.js');
8+
assert.strictEqual(typeof fn, 'function');
9+
});
10+
it('should return a filter function that matches the glob', () => {
11+
const fn = path.glob('*.js');
12+
assert.strictEqual(fn('foo.js'), true);
13+
});
14+
});
15+
16+
describe('path.globToRegExp', () => {
17+
it('should return a RegExp', () => {
18+
const re = path.globToRegExp('foo');
19+
assert.strictEqual(re instanceof RegExp, true);
20+
});
21+
it('should return a RegExp that matches the glob', () => {
22+
const re = path.globToRegExp('*.js');
23+
assert.strictEqual(re.test('foo.js'), true);
24+
})
25+
});

0 commit comments

Comments
 (0)