Node.js 词条目录
前端Wiki/词条/fs 文件系统模块

fs 文件系统模块

定义Node 内置的文件读写模块:同步、异步回调与 Promise 三套 API

fs 提供 fs.readFile(读整个文件)、fs.writeFile(覆盖写)、fs.createReadStream(流式)、fs.appendFile(追加)、fs.readdir(列目录)、fs.stat(元信息:大小/修改时间/是否目录)。每类 API 多数有三种形态:同步版(readFileSync,阻塞事件循环,只在启动期用)、回调版(readFile(err, data))、Promise 版(fs/promises 的 await 风格)。

新代码一律用 fs/promises + async/await,错误处理用 try/catch。路径处理结合 path 模块(path.join 代替字符串拼接,跨平台分隔符)。读大文件用流;追加日志 appendFile 不会覆盖;判断文件存在别用 fs.exists(已废弃),catch readFile 的 ENOENT 才是正解。

JavaScript
const fs = require('fs/promises');   // ★ Promise 版
const path = require('path');

async function readConfig() {
  try {
    const data = await fs.readFile(
      path.join(__dirname, 'config.json'),
      'utf-8',                    // 不传返回 Buffer
    );
    return JSON.parse(data);
  } catch (err) {
    if (err.code === 'ENOENT') return {};    // 文件不存在 → 兜底
    throw err;
  }
}

await fs.writeFile('out.log', 'hello\n');   // 覆盖写
await fs.appendFile('out.log', 'more\n');   // 追加
await fs.mkdir('logs', { recursive: true }); // 递归建目录

const files = await fs.readdir('logs');      // 列目录
const st = await fs.stat('logs');            // 元信息
console.log(st.isDirectory(), st.size, st.mtime);
⚠ 常见误区
🔗 相关词条Stream 流Buffer 二进制数据Node.js 是什么
← 返回来源章节读写文件