Sometimes, you might want to convert a JavaScript function that accepts a callback to one that returns a Promiseobject. This lesson shows how to manually wrap a promise-based API around the fs.readFile() function. It also explains how to use the util.promisify() method that is built into the Node.js standard library.

 
const fs = require('fs')

function readFile(path, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(path, encoding, (error, contents) => {
if (error) {
reject(error)
} else {
resolve(contents)
}
})
})
} readFile(__filename, "utf8")
.then((contents) => {
console.log(contents)
}, error => {
console.error(error)
})

In nodejs we can use util function:

const fs = require("fs");
const util = require("util"); const readFile = util.promisify(fs.readFile); readFile(__filename, "utf8").then(
contents => {
console.log(contents);
},
error => {
console.error(error);
}
);

最新文章

  1. C语言中如何判断文件是否存在
  2. winfrom 隐藏任务栏(win7)
  3. Linux 改进捕捉信号机制(sigaction,sigqueue)
  4. POJ-2152 Fire (树形DP)
  5. HDU 4336-Card Collector(状压,概率dp)
  6. mht文件无法打开的解决办法
  7. 常用PC服务器LSI阵列卡配置
  8. HttpApplication事件执行顺序(转)
  9. unity3d插件Daikon Forge GUI 中文教程-5-高级控件listbox和progress bar的使用
  10. [Swust OJ 1132]-Coin-collecting by robot
  11. (Sqlyog或Navicat不友好处)SHOW ENGINE INNODB STATUS 结果为空或结果为=====================================
  12. Ubuntu 16.04 安装PCL库以及测试
  13. 安全之路 —— 使用Windows全局钩子打造键盘记录器
  14. springboot 传List参数
  15. linux shell中如何往所有行尾添加内容
  16. numpy.asmatrix的用法
  17. vue watch,computed,metods的区别
  18. iframe父页面获取iframe子页面的元素 与 iframe子页面获取父页面元素
  19. yum安装apache及问题解决
  20. HDU 1711 Number Sequence (KMP简单题)

热门文章

  1. 模块导入及使用,关键字,模块搜索路径,python文件的两种用途
  2. python面向对象(反射)(四)
  3. (原)UICollectionView的基本使用
  4. LeetCode(107) Binary Tree Level Order Traversal II
  5. nw335 debian sid x86-64 -- 5 使用xp的驱动
  6. python基础——12(包的概念)
  7. django的rest framework框架——认证、权限、节流控制
  8. POJ-3261 Milk Patterns,后缀数组+二分。。
  9. HackerRank# Red John is Back
  10. bzoj1411: [ZJOI2009]硬币游戏