fs-extra
是 Node.js 的一个文件系统操作库,扩展并增强了原生的 fs
(文件系统)模块,提供了更多高级功能,简化了文件和目录操作。它的主要作用包括:
1. 增强的 fs
功能
fs-extra
兼容 Node.js 原生的fs
模块,提供了与fs
相同的所有 API,因此可以用fs-extra
完全替代fs
。- 通过 Promises API 支持异步操作,例如
fs.promises
,避免了回调地狱。
2. 额外的功能
- 递归创建目录(
mkdirp
):可以一次性创建多级目录,而无需手动检查父目录是否存在。
const fs = require('fs-extra');
fs.mkdirp('/tmp/some/long/path')
.then(() => console.log('Directory created!'))
.catch(err => console.error(err));
- 递归删除目录和文件(
remove
):允许删除目录及其所有子目录和文件。
fs.remove('/tmp/some/dir')
.then(() => console.log('Directory removed!'))
.catch(err => console.error(err));
- 复制文件和目录(
copy
):可以将文件或目录递归复制到目标位置。
fs.copy('/tmp/file.txt', '/tmp/backup/file.txt')
.then(() => console.log('File copied!'))
.catch(err => console.error(err));
- 移动文件或目录(
move
):允许重命名或移动文件和目录,支持跨文件系统操作。
fs.move('/tmp/file.txt', '/tmp/new-dir/file.txt')
.then(() => console.log('File moved!'))
.catch(err => console.error(err));
- 读取和写入 JSON(
readJson
、writeJson
):提供了简单的 API 直接读取和写入 JSON 文件。
fs.readJson('/tmp/config.json')
.then(obj => console.log(obj))
.catch(err => console.error(err));
fs.writeJson('/tmp/config.json', { name: 'test' })
.then(() => console.log('JSON written!'))
.catch(err => console.error(err));
- 确保文件存在(
ensureFile
):如果文件不存在,会自动创建该文件。
fs.ensureFile('/tmp/somefile.txt')
.then(() => console.log('File ensured!'))
.catch(err => console.error(err));
- 确保目录存在(
ensureDir
):确保目录存在,如果不存在就创建它。
fs.ensureDir('/tmp/some/dir')
.then(() => console.log('Directory ensured!'))
.catch(err => console.error(err));
3. Promise 支持
fs-extra
的所有方法都支持 Promise,因此可以直接使用async/await
语法,简化了异步代码的书写。相比原生fs
的回调风格,fs-extra
的 Promise API 使用更加现代化,且可读性更强。
4. 常见场景简化
fs-extra
通过添加一些常见的文件操作功能,极大地简化了日常开发中的文件处理需求。例如,递归删除目录、递归创建目录、复制和移动目录树等操作在原生 fs
中需要自己手动实现,而 fs-extra
则提供了开箱即用的解决方案。
总结
fs-extra
的作用在于为 Node.js 提供更加丰富、方便的文件操作功能,减少开发者对文件系统操作的复杂性。它集成了许多实用功能,使得代码更加简洁、优雅,适合处理各种文件操作需求。