nodejs 使用fs.read读取文件
用到了promise的递归调用,因为不太会用promise,记录一下,这个代码读取中文文本时有概率乱码,因为读取的间隔是100,可能就把中文给分割开了
// 读取文件
function readData(path,encoding){
return new Promise((resolve,reject)=>{
fs.open(path, 'r',(err,fd)=>{
if(err){
log(err);
return;
}
let bufs = buffer.Buffer.alloc(100,encoding);
let str = "";
resolve(readBuffers(fd,bufs,str))
})
})
}
function readBuffers(fd,bufs,str) {
return new Promise((resolve,reject)=>{
fs.read(fd,bufs,0,bufs.length,null,(err,length,buffer)=>{
if(err){
reject(err);
}
if(length!=0){
str+= buffer.slice(0, length).toString()
resolve(readBuffers(fd,bufs,str))
}else{
resolve(str);
}
})
})
}