Node.js 的内置模块 fs(File System,文件系统)提供了操作系统文件的核心能力。通过 fs 模块,你可以完成文件的读写、创建、删除、重命名,以及目录的创建、遍历、删除等操作。 该模块内置在 Node.js 中,无需额外安装,同时支持异步回调、同步阻塞、Promise 三种调用方式,是 Node.js 服务端开发中处理文件的核心模块。
node 命令可以在终端中直接执行 JavaScript 文件。
创建一个 JavaScript 文件,如 hello-world.js,编写代码:
console.log('Hello Node.js!')打开终端,进入文件所在目录,执行命令:
node hello-world.js执行成功后,终端会输出对应的打印内容。
fs 是 Node.js 内置模块,直接导入即可使用,支持两种模块化规范:
// 1. CommonJS 规范(Node.js 默认,最常用)
const fs = require('fs')
// 2. ES Module 规范(现代推荐,需在 package.json 中配置 "type": "module")
import fs from 'fs'直接拼接路径(__dirname + '/file.txt')容易出现跨系统路径错误(Windows 用 \,Mac/Linux 用 /)。 推荐搭配 Node.js 内置 path 模块拼接路径:
const fs = require('fs')
const path = require('path')
// 安全拼接绝对路径(跨系统兼容)
const filePath = path.join(__dirname, 'files', 'test.txt')fs 模块提供了异步、同步、Promise 三类方法,以下是高频操作:
非阻塞执行,通过回调函数接收结果,生产环境推荐。
const fs = require('fs')
const path = require('path')
// 拼接安全路径
const filePath = path.join(__dirname, 'files', 'test.txt')
// 参数:文件路径、编码格式、回调函数
fs.readFile(filePath, 'utf8', (err, data) => {
// 错误优先处理
if (err) {
console.error('文件读取失败:', err)
return
}
console.log('文件内容:', data)
})阻塞程序执行,直到操作完成,适合简单脚本。
try {
const data = fs.readFileSync(filePath, 'utf8')
console.log('文件内容:', data)
} catch (err) {
console.error('文件读取失败:', err)
}writeFile写入文件:文件不存在则创建,文件存在则默认覆盖内容。
const fs = require('fs')
const path = require('path')
const filePath = path.join(__dirname, 'files', 'test1.txt')
// 写入文本内容
fs.writeFile(filePath, 'Hello my first node.js', 'utf8', (err) => {
if (err) {
console.error('文件写入失败:', err)
} else {
console.log('文件写入成功')
}
})通过 flag: 'a' 参数实现文件追加,不覆盖原有内容:
fs.writeFile(filePath, '\n追加的内容', { encoding: 'utf8', flag: 'a' }, (err) => {
if (!err) console.log('追加成功')
})补全目录创建、读取、重命名、删除的完整示例:
const fs = require('fs')
const path = require('path')
const dirPath = path.join(__dirname, 'my-folder')
// 1. 创建目录(递归创建多级目录)
fs.mkdir(dirPath, { recursive: true }, (err) => {
if (!err) console.log('目录创建成功')
})
// 2. 读取目录内容
fs.readdir(__dirname, (err, files) => {
console.log('当前目录文件:', files)
})
// 3. 重命名文件/目录
fs.rename(dirPath, path.join(__dirname, 'new-folder'), () => {})
// 4. 删除文件
fs.unlink(path.join(__dirname, 'test.txt'), () => {})
// 5. 删除空目录
fs.rmdir(dirPath, () => {})箭头函数是 ES6 新增的函数语法,常用于 fs 模块的回调函数,简化代码。
// 无参数
const func1 = () => {}
// 单个参数(可省略括号)
const func2 = param => {}
// 多个参数
const func3 = (param1, param2) => {}
// 单行返回值(省略 return 和大括号)
const add = (a, b) => a + b语法简洁:大幅缩短回调函数代码
无独立 this:继承父作用域的 this,解决传统函数的指向问题
不能用作构造函数:无法使用 new 调用
无 arguments 对象
// 传统函数
const sum = function(a, b) {
return a + b
}
// 箭头函数(简化版)
const sumArrow = (a, b) => a + b
console.log(sum(2, 3))
console.log(sumArrow(2, 3))fs 模块的核心设计:异步非阻塞(Node.js 精髓),同步方法仅适合简单场景。
现代方案:Promise 版 fs(解决回调地狱)
Node.js 提供 fs/promises,支持 async/await,最优写法:
// 导入 Promise 版 fs
const fs = require('fs/promises')
const path = require('path')
// 使用 async/await 读取文件
async function readFile() {
try {
const data = await fs.readFile(path.join(__dirname, 'test.txt'), 'utf8')
console.log(data)
} catch (err) {
console.error(err)
}
}
readFile()文件操作必须做错误处理:
异步方法:回调函数第一个参数为错误对象(错误优先)
同步方法:使用 try/catch 捕获异常
Promise 方法:使用 try/catch 或 .catch()
编码格式:默认 null(返回 Buffer 二进制数据),常用 utf8(字符串)
flag 参数:r 只读、w 写入覆盖、a 追加写入
recursive:创建多级目录时必须配置为 true
文件路径不要使用反斜杠 \,推荐用 path 模块拼接
全局脚本权限问题:以管理员身份运行终端即可解决
核心工具:fs 操作文件,path 处理路径,二者搭配使用
操作方式:优先使用 fs/promises + async/await,避免回调地狱
关键规则:异步不阻塞(生产推荐),同步阻塞(仅测试用)
代码简化:文件操作的回调函数优先使用箭头函数