node fs-文件系统 读取文件 封装promise 用trim()去掉左右两边空白结束符

参考视频: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() 方法处理一下就可以了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值