fs: refactoring declaratively with Array.fromAsync

Refs: https://github.com/nodejs/node/pull/51912
PR-URL: https://github.com/nodejs/node/pull/54644
Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com>
This commit is contained in:
Sonny 2024-09-27 18:59:09 +09:00 committed by GitHub
parent 772b35bdc4
commit 090add7864
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 40 additions and 4 deletions

View File

@ -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);
}

View File

@ -25,6 +25,7 @@
'use strict';
const {
ArrayFromAsync,
ArrayPrototypePush,
BigIntPrototypeToString,
Boolean,
@ -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);

View File

@ -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>