参考视频:B站-老陈打码-node系列课程视频链接
参考文档:node.js中文网-fs
node读取文件的小练习
首先 我们需要在要用到的文件里导入node的 文件模块
var fs = require('fs');
node 特点之一是 非阻塞IO模型(异步),那集成方法也都是异步的比较常用,不过也有同步的方法,可对比看下
同步:
var fd = fs.openSync('hello.txt', "r")
console.log(fd) //3
var content = fs.readFileSync(fd)
console.log(content) //<Buffer 68 65 6c 6c 6f 77 6f 72 6c 64>
console.log(content.toString()) //helloworld
同步总是存在等待和阻塞,所以还是用异步比较靠谱。
异步:
fs.readFile("hello.txt", {
flag: 'r',
encoding: 'utf-8'
}, function (err, data) {
if (err) {
console.log(err)
} else {
console.log(data)
}
console.log(456)
})
console.log(123)
//123
//helloworld
//456
为了取得和同步一样的效果,我们会使用到回调函数,但是层层回调的情况又容易出现回调地域的情况,所以我们封装个promise来解决这种问题。
function fsRead(path) {
return new Promise(function (resolve, reject) {
fs.readFile(path, {
flag: 'r',
encoding: 'utf-8'
}, function (err, data) {
if (err) {
//console.log(err)
//失败执行的内容
reject(err)
} else {
//console.log(data)
//成功执行的内容
resolve(data)
}
//console.log(456)
})
})
}
封装好啦,应用起来,下面这个例子模拟了三个文件之间的调用。asycn和await写起来,更有异步的风格了~
async function ReadList() {
var file2 = await fsRead('hello.txt')
var file3 = await fsRead(file2.trim() + ".txt")//去掉左右两边空白结束符
var file3Content = await fsRead(file3 + ".txt")
console.log(file3Content)
}
ReadList();//hello第三个文件
PS:如果取不到结果但是文件代码没问题的情况下,可能是文件里面有空白结束符,用trim() 方法处理一下就可以了