node.js - 将 async/await 与 util.promisify(fs.readFile) 一起使用?
问题描述
我正在尝试学习 async/await,您的反馈会很有帮助。
我只是将 fs.readFile() 用作尚未使用 Promises 和 async/await 进行现代化改造的函数的具体示例。
(我知道 fs.readFileSync() 但我想学习这些概念。)
下面的模式是一个好的模式吗?有什么问题吗?
const fs = require('fs');
const util = require('util');
//promisify converts fs.readFile to a Promised version
const readFilePr = util.promisify(fs.readFile); //returns a Promise which can then be used in async await
async function getFileAsync(filename) {
try {
const contents = await readFilePr(filename, 'utf-8'); //put the resolved results of readFilePr into contents
console.log('✔️ ', filename, 'is successfully read: ', contents);
}
catch (err){ //if readFilePr returns errors, we catch it here
console.error('⛔ We could not read', filename)
console.error('⛔ This is the error: ', err);
}
}
getFileAsync('abc.txt');
解决方案
而是从 fs/promises 导入,如下所示:
const { readFile } = require('fs/promises')
此版本返回您要使用的承诺,然后您无需手动将 readFile 包装在承诺中。
推荐阅读
- node.js - Node.js:衡量有多少任务正在等待运行的指标
- maven - 使用带有 OSGI 蓝图的骆驼 maven 插件
- c++ - 如何搜索文件并将其从一个路径移动到另一个 C++?
- java - 如何从 Intent 或 SharedPreferences 获取数据
- excel - 需要 Excel 形式的 Jython 输出
- django - Django DRF当文件为空时更新它会给出错误 - 选择文件时它可以工作
- azure-devops - 如何在 Azure DevOps 管道中使用复杂变量
- swift - 本地保存数据(IOS)
- r - gt table - 单元格中的换行符
- reactjs - 在表单提交时导航到另一个组件并将数据传递给导航组件反应 Js