ES Module 和 CJS的区别
- CJS 同步加载模块,ES Module异步加载模块。因此ES Module的加载速度快于CJS
- ES Module更加适配现在的浏览器环境
因此一般建议使用ES Module
读文件
readFile 异步函数 返回一个Promise对象
接受两个参数:
1.path string 类型(文件路径)
2.options 一般用来指定编码方式,常见的有'utf-8'
import { readFile } from 'node:fs/promise';
const content = await readFile('./data.json','utf-8');
console.log(content);
readfile 同步函数 返回void
接受三个参数:
1.path string类型 指定文件路径
2.options 指定编码方式
3.callback 回调函数(err,data)
import { readFile } from 'node:fs';
readFile('./data.json','utf-8',(err,data)=>{
if(err) throw err;
console.log(data)
})
写文件
writeFile 异步函数 返回一个primse对象
接受三个参数:
1.file string类型 文件路径
2.data string类型 写入的数据
3.options 一般用来指定编码方式,常见的有'utf-8'
import { writeFile } from "node:js/promises";
const data = 'good morning!';
await writeFile('./message.txt',data,'utf-8');
writeFile 同步函数 返回void
接受四个参数
1.file 文件路径
2.data 写入的文件内容
3.options 编码方式
4.callback 回调函数(err)
import { writeFile } from 'node:fs';
const data = 'good afternoon';
writeFile('./message.txt',data,'utf-8',(err)=>{
if(err) throw err;
console.log('The file has been saved')
})
注意writeFile并不是追加,而是将文本内容清空后写入数据。如果想要对文本追加内容,请使用appendFile,方法与writeFile类似