Skip to content

Commit 090add7

Browse files
authored
fs: refactoring declaratively with Array.fromAsync
Refs: #51912 PR-URL: #54644 Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com>
1 parent 772b35b commit 090add7

File tree

3 files changed

+40
-4
lines changed

3 files changed

+40
-4
lines changed

benchmark/fs/bench-glob.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const fs = require('fs');
5+
const path = require('path');
6+
const assert = require('node:assert');
7+
8+
const benchmarkDirectory = path.resolve(__dirname, '..', '..');
9+
10+
const configs = {
11+
n: [1e3],
12+
dir: ['lib'],
13+
pattern: ['**/*', '*.js', '**/**.js'],
14+
mode: ['async', 'sync'],
15+
recursive: ['true', 'false'],
16+
};
17+
18+
const bench = common.createBenchmark(main, configs);
19+
20+
async function main(config) {
21+
const fullPath = path.resolve(benchmarkDirectory, config.dir);
22+
const { pattern, recursive, mode } = config;
23+
24+
let noDead;
25+
bench.start();
26+
27+
for (let i = 0; i < config.n; i++) {
28+
if (mode === 'async') {
29+
noDead = await fs.promises.glob(pattern, { cwd: fullPath, recursive });
30+
} else {
31+
noDead = fs.globSync(pattern, { cwd: fullPath, recursive });
32+
}
33+
}
34+
35+
bench.end(config.n);
36+
assert.ok(noDead);
37+
}

lib/fs.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
'use strict';
2626

2727
const {
28+
ArrayFromAsync,
2829
ArrayPrototypePush,
2930
BigIntPrototypeToString,
3031
Boolean,
@@ -3115,10 +3116,7 @@ function glob(pattern, options, callback) {
31153116
// TODO: Use iterator helpers when available
31163117
(async () => {
31173118
try {
3118-
const res = [];
3119-
for await (const entry of new Glob(pattern, options).glob()) {
3120-
ArrayPrototypePush(res, entry);
3121-
}
3119+
const res = await ArrayFromAsync(new Glob(pattern, options).glob());
31223120
callback(null, res);
31233121
} catch (err) {
31243122
callback(err);

typings/primordials.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ declare namespace primordials {
111111
export const ArrayPrototype: typeof Array.prototype
112112
export const ArrayIsArray: typeof Array.isArray
113113
export const ArrayFrom: typeof Array.from
114+
export const ArrayFromAsync: typeof Array.fromAsync
114115
export const ArrayOf: typeof Array.of
115116
export const ArrayPrototypeConcat: UncurryThis<typeof Array.prototype.concat>
116117
export const ArrayPrototypeCopyWithin: UncurryThis<typeof Array.prototype.copyWithin>

0 commit comments

Comments
 (0)