Skip to content

Commit

Permalink
fs: refactoring declaratively with Array.fromAsync
Browse files Browse the repository at this point in the history
Refs: #51912
PR-URL: #54644
Reviewed-By: Daeyeon Jeong <[email protected]>
  • Loading branch information
sonsurim authored Sep 27, 2024
1 parent 772b35b commit 090add7
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
37 changes: 37 additions & 0 deletions benchmark/fs/bench-glob.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const common = require('../common');
const fs = require('fs');
const path = require('path');
const assert = require('node:assert');

const benchmarkDirectory = path.resolve(__dirname, '..', '..');

const configs = {
n: [1e3],
dir: ['lib'],
pattern: ['**/*', '*.js', '**/**.js'],
mode: ['async', 'sync'],
recursive: ['true', 'false'],
};

const bench = common.createBenchmark(main, configs);

async function main(config) {
const fullPath = path.resolve(benchmarkDirectory, config.dir);
const { pattern, recursive, mode } = config;

let noDead;
bench.start();

for (let i = 0; i < config.n; i++) {
if (mode === 'async') {
noDead = await fs.promises.glob(pattern, { cwd: fullPath, recursive });
} else {
noDead = fs.globSync(pattern, { cwd: fullPath, recursive });
}
}

bench.end(config.n);
assert.ok(noDead);
}
6 changes: 2 additions & 4 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
'use strict';

const {
ArrayFromAsync,
ArrayPrototypePush,
BigIntPrototypeToString,
Boolean,
Expand Down Expand Up @@ -3115,10 +3116,7 @@ function glob(pattern, options, callback) {
// TODO: Use iterator helpers when available
(async () => {
try {
const res = [];
for await (const entry of new Glob(pattern, options).glob()) {
ArrayPrototypePush(res, entry);
}
const res = await ArrayFromAsync(new Glob(pattern, options).glob());
callback(null, res);
} catch (err) {
callback(err);
Expand Down
1 change: 1 addition & 0 deletions typings/primordials.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ declare namespace primordials {
export const ArrayPrototype: typeof Array.prototype
export const ArrayIsArray: typeof Array.isArray
export const ArrayFrom: typeof Array.from
export const ArrayFromAsync: typeof Array.fromAsync
export const ArrayOf: typeof Array.of
export const ArrayPrototypeConcat: UncurryThis<typeof Array.prototype.concat>
export const ArrayPrototypeCopyWithin: UncurryThis<typeof Array.prototype.copyWithin>
Expand Down

0 comments on commit 090add7

Please sign in to comment.