技术 · 思考 · 实践 · 成长

首页/Node/正文

Node.js 核心模块:fs 文件系统与 path 路径

Node5 次阅读

fs(文件系统)与 path(路径)是 Node 最常用的核心模块。本文讲读写的三种姿势与路径处理,结尾附批量处理小案例。

一、读文件三种姿势

const fs = require('fs');

// 1. 同步(阻塞,简单脚本用)
const data = fs.readFileSync('a.txt', 'utf8');

// 2. 异步回调(经典)
fs.readFile('a.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

// 3. Promise(现代推荐)
const fsP = require('fs').promises;
const data2 = await fsP.readFile('a.txt', 'utf8');

二、fs 常用方法表

方法作用
readFile / writeFile读/写整个文件
appendFile追加写入(日志)
existsSync判断存在(老)→ 用 fs.existsSync 或 access
mkdir / rmdir建/删目录(recursive:true 递归)
readdir读目录列表
unlink删除文件
rename重命名/移动
stat文件信息(大小/时间)
copyFile复制
createReadStream/WriteStream流式(大文件)

三、path 模块

const path = require('path');

path.join('/a', 'b', 'c.txt');     // /a/b/c.txt(拼接)
path.resolve('./a', 'b.txt');      // /当前目录/a/b.txt(绝对)
path.basename('/a/b/c.txt');        // c.txt
path.dirname('/a/b/c.txt');         // /a/b
path.extname('c.txt');              // .txt
path.parse('/a/b/c.txt');           // {root,dir,base,ext,name}
__dirname                          // 当前文件所在目录(CommonJS)

路径拼接永远用 path.join —— 别手拼字符串(Windows 反斜杠坑)。

四、目录操作

// 递归建目录
fs.mkdirSync('/a/b/c', { recursive: true });

// 遍历目录(递归)
async function walk(dir) {
    for (const f of await fsP.readdir(dir, { withFileTypes: true })) {
        const full = path.join(dir, f.name);
        f.isDirectory() ? await walk(full) : console.log(full);
    }
}

五、大文件用流

const read  = fs.createReadStream('big.log');
const write = fs.createWriteStream('copy.log');
read.pipe(write);                  // 边读边写,不占内存
read.on('end', () => console.log('完成'));

readFile 整个进内存(大文件会爆)、Stream 分块处理 —— 1GB 日志就靠它。

六、注意

  • 服务端尽量用异步/Promise(同步阻塞事件循环);
  • existsSync 简单场景可用,精细判断用 fs.access;
  • 写文件注意路径穿越(别让用户输入拼路径);
  • __dirname 是 CommonJS 的,ES Module 用 import.meta.url。

七、小案例:日志文件批量处理

const fs = require('fs').promises;
const path = require('path');

async function cleanLogs(logDir, days = 7) {
    const cutoff = Date.now() - days * 86400000;
    const files = await fs.readdir(logDir);
    let removed = 0;

    for (const f of files) {
        if (!f.endsWith('.log')) continue;
        const full = path.join(logDir, f);
        const stat = await fs.stat(full);
        if (stat.mtimeMs < cutoff) {
            await fs.unlink(full);
            removed++;
        }
    }
    console.log(`清理 ${removed} 个 ${days} 天前的日志`);
}

// 统计目录大小
async function dirSize(dir) {
    let size = 0;
    for (const f of await fs.readdir(dir, { withFileTypes: true })) {
        const full = path.join(dir, f.name);
        size += f.isDirectory() ? await dirSize(full) : (await fs.stat(full)).size;
    }
    return size;
}

(async () => {
    await cleanLogs('./logs', 7);
    console.log('目录大小:', (await dirSize('./logs') / 1024).toFixed(1) + 'KB');
})();

readdir + stat + unlink 批量清理 + 递归统计大小 —— 运维脚本的 fs 标准套路。

八、总结

fs 三姿势(sync/回调/Promise),大文件走 Stream;path.join 拼路径、basename/extname 取部件;批量操作用 fs.promises;日志清理是练手好题。

照顾好自己,如果尚有余力,记得保护美好的东西,不畏不惧赤诚善良。

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读