第一步:引入fs系统模块
const fs = require('fs')
文件读取
fs.readFile(path,[option(可选参数)],callback)
- 参数一:字符串 必选 文件路径
- 参数二: 可选参数 表示以什么方式进行编码
- 参数三: 回调函数 表示前面文件读取完成之后,可以通过回调函数拿到文件
❀异步读取文件:
❀语法:fs.readFile(文件路径,['文件编码'],callback);
♥readFile当省略参数2时,文件读取成功返回例:<Buffer 30 31>数据,此时需要data.toString()转码才能返回正确字符串
♥callback 回调函数
♥回调函数有两个参数,并且参数位置不能错位
①erray 读取失败
②data 读取成功
实例:
♥fs.readFile('./index.txt', 'utf-8', (err, data) => {
if (err) {
console.log(err);
return false;
}
console.log(data);
})
♥利用promise优化异步读取文件:
写法1:
let pro = new Promise((reslove, reject) => {
fs.readFile('./index.txt', 'utf-8', (err, data) => {
if (err) {
reject(err)
}
reslove(data)
})
})
pro.then((result) => {console.log(result)})
.catch((err) => { console.log(err); });
写法2:引入fs模块里的promise的Api
const fsPromise = require('fs').promises;
fsPromise.readFile('./index.txt', 'utf-8')
.then((result) => { console.log(result); })
.catch((err) => { console.log(err); });
简化:省略内部箭头函数传参过程
fsPromise.readFile('./index.txt', 'utf-8')
.then(console.log)
.catch(console.error);
❀同步读取文件:
语法:
fs.readFileSync('文件路径',['文件编码'])
实例:
const data = fs.readFileSync('./08.txt', 'utf-8')
console.log(data)