chokidar、fsevents、gaze、node-watch 和 watchpack 主要用于监听文件系统变化,而 fs-extra 则专注于增强 Node.js 原生的文件系统操作能力。在构建开发服务器、打包工具或自动化脚本时,选择合适的监听库至关重要,它直接影响应用的启动速度、CPU 占用率以及跨平台兼容性。chokidar 是目前社区最通用的选择,它封装了 fsevents 以在 macOS 上获得高性能,同时兼容其他系统。fs-extra 虽然不是监听库,但常与监听工具配合使用,提供如 ensureDir、copy 等原子化操作。理解这些工具的底层机制和适用场景,能帮助开发者避免内存泄漏和无效的重建触发。
在 Node.js 生态中,处理文件变化和操作是构建工具链的核心环节。chokidar、fsevents、gaze、node-watch、watchpack 以及 fs-extra 各自解决了不同层面的问题。有些专注于高效监听,有些专注于文件操作便利性,还有些专为打包工具设计。让我们从架构师的角度,深入分析它们的实现机制、API 设计以及适用边界。
文件监听的性能很大程度上取决于是否使用了操作系统的原生能力。
chokidar 是一个跨平台的封装层。它在 macOS 上会自动使用 fsevents,在 Linux 上使用 inotify,在 Windows 上使用 ReadDirectoryChangesW。这种策略保证了性能与兼容性的平衡。
// chokidar: 自动选择底层实现
const chokidar = require('chokidar');
const watcher = chokidar.watch('src/**/*.js', {
ignored: /node_modules/,
persistent: true
});
watcher.on('change', path => console.log(`File ${path} has been changed`));
fsevents 直接调用 macOS 的 FSEvents API。它是目前 macOS 上性能最高的监听方案,但完全不具备跨平台能力。
// fsevents: 仅限 macOS
const fsevents = require('fsevents');
const stop = fsevents('./', (path, flags, id) => {
console.log('Event:', path, flags, id);
});
// 需要手动管理停止监听
stop();
node-watch 完全基于 Node.js 原生的 fs.watch 和 fs.stat 实现,不依赖任何 C++ 插件。这使得它在任何 Node 环境中都能运行,但性能略低于原生方案。
// node-watch: 纯 JS 实现
const watch = require('node-watch');
watch('./src', { recursive: true, filter: /.js$/ }, (evt, name) => {
console.log('%s changed.', name);
});
watchpack 是 Webpack 内部使用的监听器。它针对大量文件进行了优化,采用聚合触发机制,避免频繁的重建。
// watchpack: 面向打包工具优化
const Watchpack = require('watchpack');
const wp = new Watchpack({
aggregateTimeout: 1000
});
wp.watch({ files: ['index.js'], directories: ['src'] }, 0);
wp.on('aggregated', (changes, removals) => {
console.log('Changes:', changes, 'Removals:', removals);
});
gaze 是早期的 glob 监听库,基于 fs.watch。由于历史原因,它在处理大量文件时容易出现性能瓶颈,且目前已不再维护。
// gaze: 旧式 Glob 监听 (不推荐)
const gaze = require('gaze');
gaze('**/*.js', function(err, watcher) {
watcher.on('changed', function(filepath) {
console.log(filepath, 'was changed');
});
});
fs-extra 并不提供监听功能,它是对 fs 模块的增强。它常用于监听触发后的文件操作,如移动或复制。
// fs-extra: 文件操作增强 (非监听)
const fse = require('fs-extra');
async function moveFile() {
await fse.move('/src/file.txt', '/dest/file.txt', { overwrite: true });
await fse.ensureDir('/dest/logs');
}
在选择依赖时,库的维护状态直接关系到项目的长期稳定性。
chokidar:目前维护最活跃,是社区事实上的标准。Vite、Webpack 等主流工具均在其底层或推荐配置中使用它。fsevents:持续维护,但仅作为底层依赖存在。除非你明确知道自己在做什么,否则不建议直接在应用层引入。gaze:已弃用 (Deprecated)。其 GitHub 仓库已归档,存在未修复的内存泄漏问题。新项目中绝对不应使用。node-watch:维护状态稳定,更新频率较低,适合简单场景。watchpack:由 Webpack 团队维护,稳定可靠,但文档主要面向插件开发者。fs-extra:非常稳定,广泛使用,是 Node.js 文件操作的事实标准扩展。不同的 API 设计反映了库的设计哲学:是追求简单,还是追求控制力。
chokidar 和 gaze 采用 EventEmitter 模式,适合处理复杂的生命周期。
// chokidar: 丰富的生命周期事件
watcher
.on('add', path => console.log(`File ${path} was added`))
.on('unlink', path => console.log(`File ${path} was removed`))
.on('error', error => console.log(`Watcher error: ${error}`));
node-watch 的 API 更加函数式,适合快速脚本。
// node-watch: 简洁的回调风格
watch('./src', (evt, name) => {
if (evt === 'update') {
console.log('File updated:', name);
}
});
fs-extra 提供了 Promise 支持,这在现代 async/await 代码中非常关键。
// fs-extra: 原生支持 Promise
const fs = require('fs-extra');
async function initProject() {
// 如果目录不存在则创建,存在则忽略
await fs.ensureDir('./build/assets');
// 读取并解析 JSON,自动处理异常
const data = await fs.readJson('./config.json');
return data;
}
相比之下,使用原生 fs 或其他监听库处理文件内容时,往往需要额外的包装。
在大型项目中,文件监听器的效率直接影响开发体验。
fsevents:在 macOS 上几乎零 CPU 占用,因为它直接由系统内核通知。chokidar:在 macOS 上表现与 fsevents 相当。在 Windows 上,由于轮询机制的开销,可能会占用更多资源,但它是 Windows 上最稳定的选择。watchpack:针对“文件爆发”场景优化。当一次保存触发多个文件变更时,它会聚合事件,减少构建次数。gaze:在处理数千个文件时,内存占用显著高于 chokidar,且容易丢失事件。推荐:watchpack 或 chokidar
如果你需要与 Webpack 深度集成,watchpack 是内部一致的选择。如果是通用插件,chokidar 兼容性更好。
// 插件中集成 chokidar
const watcher = chokidar.watch(options.paths);
watcher.on('change', (file) => {
compilation.invalidate(file);
});
推荐:chokidar
必须保证在 Windows、macOS 和 Linux 上行为一致。
// 开发服务器监听静态文件
const server = chokidar.watch('public', { ignoreInitial: true });
server.on('all', (event, path) => {
io.emit('reload', path);
});
推荐:node-watch
无需安装原生模块,部署简单,适合一次性脚本或 Serverless 环境。
// 备份脚本
watch('./data', { recursive: true }, () => {
exec('rsync -av ./data/ ./backup/');
});
推荐:fs-extra
配合监听器使用,处理具体的文件 IO。
// 监听日志文件并归档
watcher.on('add', async (file) => {
if (file.endsWith('.log')) {
await fse.move(file, `./archive/${Date.now()}.log`);
}
});
| 特性 | chokidar | fs-extra | fsevents | gaze | node-watch | watchpack |
|---|---|---|---|---|---|---|
| 主要用途 | 通用文件监听 | 文件操作增强 | macOS 原生监听 | 旧式 Glob 监听 | 纯 JS 文件监听 | 打包工具监听 |
| 跨平台 | ✅ 优秀 | ✅ 优秀 | ❌ 仅 macOS | ✅ 一般 | ✅ 优秀 | ✅ 优秀 |
| 原生依赖 | 可选 (macOS) | ❌ 无 | ✅ 是 | ❌ 无 | ❌ 无 | ❌ 无 |
| 维护状态 | ✅ 活跃 | ✅ 活跃 | ✅ 活跃 | ❌ 已弃用 | ✅ 稳定 | ✅ 活跃 |
| Promise 支持 | ✅ 支持 | ✅ 原生支持 | ❌ 回调 | ❌ 回调 | ✅ 支持 | ✅ 支持 |
| 推荐指数 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ (IO) | ⭐⭐ (底层) | ⭐ (避免) | ⭐⭐⭐ | ⭐⭐⭐⭐ (工具) |
在现代前端工程化体系中,chokidar + fs-extra 是最稳健的组合。chokidar 负责精准、高效地感知变化,而 fs-extra 负责安全、便捷地执行文件操作。
避免直接使用 fsevents,除非你在编写类似 chokidar 这样的底层库。对于 gaze,请将其视为技术债务,尽快在重构中移除。如果你的工作是开发构建工具本身,深入研究 watchpack 的聚合机制会给你带来灵感。
记住,文件监听是资源密集型操作 —— 总是配置好 ignored 选项,排除 node_modules 和 .git 目录,这能节省 90% 以上的不必要开销。
当你需要比 Node.js 原生 fs 模块更便捷的文件操作方法时使用,例如递归创建目录或移动文件。注意它本身不提供文件监听功能,通常与 chokidar 配合使用来处理监听后的文件操作。
如果你需要构建一个跨平台的文件监听服务,chokidar 是首选。它自动处理不同操作系统的差异,并在 macOS 上利用 fsevents 提升性能。适用于大多数开发服务器、热重载(HMR)插件或自动化构建脚本。
仅在你的应用仅运行于 macOS 环境且对文件监听性能有极致要求时使用。它是原生 C++ 绑定,安装复杂且不支持 Windows 或 Linux,通常作为 chokidar 的底层依赖而非直接调用。
仅用于维护旧项目。该库已不再积极维护,且存在已知的性能问题和内存泄漏风险。在新项目中应避免使用,建议迁移至 chokidar 以获得更好的稳定性和支持。
如果你希望避免原生依赖(native dependencies)带来的安装问题,可以选择它。它完全基于 JavaScript 实现,支持递归监听,适合对安装体积敏感或环境受限的场景。
如果你正在开发类似 Webpack 的打包工具或需要处理大量文件的高性能监听场景。它针对构建工具进行了优化,支持批量处理和延迟触发,但不适合作为通用的应用层监听库。
fs-extra adds file system methods that aren't included in the native fs module and adds promise support to the fs methods. It also uses graceful-fs to prevent EMFILE errors. It should be a drop in replacement for fs.
I got tired of including mkdirp, rimraf, and ncp in most of my projects.
npm install fs-extra
fs-extra is a drop in replacement for native fs. All methods in fs are attached to fs-extra. All fs methods return promises if the callback isn't passed.
You don't ever need to include the original fs module again:
const fs = require('fs') // this is no longer necessary
you can now do this:
const fs = require('fs-extra')
or if you prefer to make it clear that you're using fs-extra and not fs, you may want
to name your fs variable fse like so:
const fse = require('fs-extra')
you can also keep both, but it's redundant:
const fs = require('fs')
const fse = require('fs-extra')
NOTE: The deprecated constants fs.F_OK, fs.R_OK, fs.W_OK, & fs.X_OK are not exported on Node.js v24.0.0+; please use their fs.constants equivalents.
There is also an fs-extra/esm import, that supports both default and named exports. However, note that fs methods are not included in fs-extra/esm; you still need to import fs and/or fs/promises seperately:
import { readFileSync } from 'fs'
import { readFile } from 'fs/promises'
import { outputFile, outputFileSync } from 'fs-extra/esm'
Default exports are supported:
import fs from 'fs'
import fse from 'fs-extra/esm'
// fse.readFileSync is not a function; must use fs.readFileSync
but you probably want to just use regular fs-extra instead of fs-extra/esm for default exports:
import fs from 'fs-extra'
// both fs and fs-extra methods are defined
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
NOTE: You can still use the native Node.js methods. They are promisified and copied over to fs-extra. See notes on fs.read(), fs.write(), & fs.writev()
walk() and walkSync()?They were removed from fs-extra in v2.0.0. If you need the functionality, walk and walkSync are available as separate packages, klaw and klaw-sync.
fse-cli allows you to run fs-extra from a console or from npm scripts.
If you like TypeScript, you can use fs-extra with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
If you want to watch for changes to files or directories, then you should use chokidar.
fs-filesystem allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
Wanna hack on fs-extra? Great! Your help is needed! fs-extra is one of the most depended upon Node.js packages. This project
uses JavaScript Standard Style - if the name or style choices bother you,
you're gonna have to get over it :) If standard is good enough for npm, it's good enough for fs-extra.
What's needed?
Note: If you make any big changes, you should definitely file an issue for discussion first.
fs-extra contains hundreds of tests.
npm run lint: runs the linter (standard)npm run unit: runs the unit testsnpm run unit-esm: runs tests for fs-extra/esm exportsnpm test: runs the linter and all testsWhen running unit tests, set the environment variable CROSS_DEVICE_PATH to the absolute path of an empty directory on another device (like a thumb drive) to enable cross-device move tests.
If you run the tests on the Windows and receive a lot of symbolic link EPERM permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the Node.js command prompt and run as Administrator. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my fs-extra directory and run the tests.
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
First, I believe that in as many cases as possible, the Node.js naming schemes should be chosen. However, there are problems with the Node.js own naming schemes.
For example, fs.readFile() and fs.readdir(): the F is capitalized in File and the d is not capitalized in dir. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: fs.mkdir(), fs.rmdir(), fs.chown(), etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: cp, cp -r, mkdir -p, and rm -rf?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call fs.remove(path). If you want to copy a file or a directory whether it has contents, just call fs.copy(source, destination). If you want to create a directory regardless of whether its parent directories exist, just call fs.mkdirs(path) or fs.mkdirp(path).
fs-extra wouldn't be possible without using the modules from the following authors:
Licensed under MIT
Copyright (c) 2011-2024 JP Richardson