node.js中fs读取文件模块与第三方then-fs读取文件模块的区别
1. node.js官方模块fs
node.js 官方提供的 fs 模块的使用:
查看代码
import fs from 'fs' fs.readFile('./files/1.txt', 'utf8').(err,result) => { if (err){ console.log(err) } console.log(result) }
2. 第三方包 then.fs(含利用.then解决回调地狱问题)
但是,node.js 官方提供的 fs 模块仅支持以回调函数的方式读取文件,不支持 Promise 的调用方式。因此,安装 then-fs 这个第三方包,才能支持基于 Promise 的方式读取文件的内容。
安装第三方包then-fs:npm i then-fs
查看代码
import thenFs from 'then-fs' thenFs.readFile('./files/1.txt', 'utf8') .then( result => {console.log( result )}, err => {console.log( err )} ) ------------------------- // .then()方法中返回的也是一个 promise 对象,那么可以继续使用 .then() 处理 // 这种通过 .then() 方法的链式调用,可以解决回调地狱问题 import thenFs from 'then-fs' thenFs.readFile('./files/11.txt', 'utf8') .then((r1) => { console.log(r1) return thenFs.readFile('./files/2.txt', 'utf8') // 返回一个新的 promise 对象 }) .then((r2) => { console.log(r2) return thenFs.readFile('./files/3.txt', 'utf8') // 继续返回一个新的 promise 对象 }) .then((r3) => { console.log(r3) })
另外,在 Promise 的链式操作中如果发生了错误,可以使用 Promise.prototype.catch 方法进行捕获和处理,例如:
查看代码
import thenFs from 'then-fs' thenFs .readFile('./files/11.txt', 'utf8') // 可以提前捕获错误,就算上面发生错误,下面代码依然可以执行 // 否则,上面发生错误,马上不继续执行下面代码 .catch((err) => { console.log(err.message) }) .then((result1) => { console.log(result1) return thenFs.readFile('./files/2.txt', 'utf8') }) .then((result2) => { console.log(result2) return thenFs.readFile('./files/3.txt', 'utf8') }) .then((result3) => { console.log(result3) })
本文来自博客园,作者:RHCHIK,转载请注明原文链接:https://www.cnblogs.com/suihung/p/16153414.html
分类:
Node.js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)