← 中文资源

简体中文版本

fs.glob 按模式匹配文件路径

用 fs.glob 匹配嵌套路径:单星号不跨目录段、双星号递归匹配、字符类收窄命中范围,遍历日志目录从此一行搞定。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

log files: [ 'logs\\2026\\11\\app-01.log', 'logs\\2026\\11\\app-02.log' ]
markdown: [ 'logs\\readme.md' ]
numbered only: [ 'logs\\2026\\11\\app-01.log', 'logs\\2026\\11\\app-02.log' ]

实现说明

fs.glob 按模式匹配文件路径以函数 logs、notes、numbered为骨架。 await 标出每个异步边界——没有 fire-and-forget。node:fs/promises 提供 mkdir、writeFile、glob——内建表面,不涉及任何包。

使用要点

  • node:fs/promises 是 Node.js 内建模块——随运行时自带,无需安装。
  • 跑完文件,输出里会留下标记——log files:、markdown:、numbered only:。

常见问题

运行之前需要装什么吗?

什么都不用装:node:fs/promises 随 Node.js 本体提供。

入口签名:const logs = (await Array.fromAsync(glob('logs/**/*.log')

核心语句

const numbered = (await Array.fromAsync(glob('logs/**/app-0[12].log'))).sort();
const logs = (await Array.fromAsync(glob('logs/**/*.log'))).sort();
const notes = (await Array.fromAsync(glob('logs/**/*.md'))).sort();

代码示例

import { mkdir, writeFile, glob } from 'node:fs/promises';

await mkdir('logs/2026/11', { recursive: true });
await writeFile('logs/2026/11/app-01.log', 'level=info');
await writeFile('logs/2026/11/app-02.log', 'level=warn');
await writeFile('logs/2026/11/app-01.log.tmp', 'scratch');
await writeFile('logs/readme.md', 'how to read logs');

// glob() returns an async iterable; Array.fromAsync collects the matches
// * matches within one path segment; ** crosses directories
const logs = (await Array.fromAsync(glob('logs/**/*.log'))).sort();
console.log('log files:', logs);

const notes = (await Array.fromAsync(glob('logs/**/*.md'))).sort();
console.log('markdown:', notes);

// [0-9] is a character class, narrowing to numbered files only
const numbered = (await Array.fromAsync(glob('logs/**/app-0[12].log'))).sort();
console.log('numbered only:', numbered);