Node.js fs 模块(上)
fs(File System)是 Node.js 核心模块,提供文件系统交互功能:读写文件、创建/删除目录、监听文件变化等。
三种调用方式
js
import fs from 'node:fs' // 回调风格(异步不阻塞)
import fs2 from 'node:fs/promises' // Promise 风格
const data = fs.readFileSync('./test.txt') // 同步(阻塞)三种方式返回的都是 Buffer,需 toString() 或指定 encoding。
常用 flag
| flag | 说明 |
|---|---|
'r' | 读取,文件不存在则报错 |
'r+' | 读写,文件不存在则报错 |
'w' | 写入,不存在则创建,存在则清空 |
'w+' | 读写,不存在则创建,存在则清空 |
'a' | 追加,不存在则创建 |
'a+' | 读取+追加,不存在则创建 |
带 x 后缀 | 路径已存在则失败(如 'wx') |
带 s 后缀 | 同步模式 |
常用 API
readFile — 读取文件
js
// 回调
fs.readFile('./index.txt', (err, data) => console.log(data.toString()))
// Promise + 指定编码
fsPromises.readFile('./index.txt', { encoding: 'utf8' }).then(console.log)
// 同步
const txt = fs.readFileSync('./index.txt')createReadStream — 流式读取(大文件)
js
const stream = fs.createReadStream('./index.txt', { encoding: 'utf8' })
stream.on('data', (chunk) => console.log(chunk))
stream.on('end', () => console.log('读取完毕'))mkdir / rm — 创建/删除目录
js
fs.mkdir('path/test/ccc', { recursive: true }, (err) => {}) // recursive 递归创建
fs.rm('path', { recursive: true }, (err) => {}) // recursive 递归删除rename — 重命名
js
fs.renameSync('./test.txt', './test2.txt')watch — 监听文件变化
js
fs.watch('./test.txt', (event, filename) => {
console.log(event, filename) // event: 'change' / 'rename'
})底层原理
fs 模块底层是 C++ 的 FSReqCallback 类对 libuv 的 uv_fs_t 的封装,异步操作通过 libuv 的事件循环实现。