fs — 文件系统
2026/7/16大约 1 分钟
fs — 文件系统
fs 模块提供文件的读写、操作等能力,支持 回调、同步、Promise 三种方式。
import * as fs from 'fs'
import * as fsPromises from 'fs/promises'
读取文件
// 回调
fs.readFile('/path/to/file', 'utf8', (err, data) => {
if (err) return console.error(err);
console.log(data);
});
// 同步
const data = fs.readFileSync('/path/to/file', 'utf8');
// Promise
const data = await fsPromises.readFile('/path/to/file', { encoding: 'utf8' });
写入文件
fs.writeFile('/path/to/file', 'content', err => {});
fs.writeFileSync('/path/to/file', 'content');
await fsPromises.writeFile('/path/to/file', 'content');
文件标志(flag)
| flag | 说明 |
|---|---|
'w' | 写入(默认),会覆盖 |
'a' | 追加 |
'a+' | 读取+追加 |
'r' | 读取(默认) |
'r+' | 读取+写入 |
fs.writeFile('/path/to/file', 'content', { flag: 'a+' }, err => {});
追加内容
fs.appendFile('file.log', 'content', err => {});
await fsPromises.appendFile('file.log', 'content');
目录操作
fs.mkdirSync('./new-dir', { recursive: true }) // 创建目录(递归创建父目录)
fs.readdirSync('/path') // 读取目录内容(返回文件名数组)
fs.rmdirSync('/path') // 删除目录
// 判断路径是否存在(推荐使用下面的方式替代 fs.exists)
try { fs.accessSync('/path', fs.constants.F_OK); } catch { /* 不存在 */ }
文件信息
const stats = fs.statSync('/path/to/file')
stats.isFile() // 是否为文件
stats.isDirectory() // 是否为目录
stats.size // 文件大小(字节)
stats.mtime // 最后修改时间
fs.stat('/path', (err, stats) => {})
文件拷贝
// 小文件
fs.copyFileSync('src.txt', 'dest.txt')
// 大文件(使用流)
fs.createReadStream('src.txt').pipe(fs.createWriteStream('dest.txt'))
遍历目录
function travel(dir, callback) {
fs.readdirSync(dir).forEach(file => {
const pathname = join(dir, file);
if (fs.statSync(pathname).isDirectory()) {
travel(pathname, callback);
} else {
callback(pathname);
}
});
}
文件监听
fs.watch('file.txt', (eventType, filename) => {
console.log(`文件 ${filename} 发生了 ${eventType} 事件`);
});
