fs(file system)文件系统管理模块
文档:
- https://nodejs.org/docs/latest-v12.x/api/fs.html
- https://www.runoob.com/nodejs/nodejs-fs.html
引入模块
const fs = require('fs');
文件读写
// 同步的方式写入
fs.writeFileSync('data.txt', 'Hello');
// 同步的方式追加写入
fs.appendFileSync('data.txt', 'World')
// 同步的方式读取, 需要制定编码,否则返回Buffer
let res = fs.readFileSync('data.txt', { encoding: 'utf-8' });
console.log(res);
// Hello
文件目录管理
// 创建文件夹
fs.mkdirSync('temp')
// 检查文件是否存在
fs.existsSync('data.txt')
// 重命名
fs.renameSync('data.txt', 'new-data.txt')
删除需慎重,略
参考 面试官:说说对 Node 中的 fs 模块的理解? 有哪些常用方法?