fs读取文件
es5
const fs = require('fs')
fs.readFile(filename,'utf8',(err,data)=>{
if(err) return reject(err)
else{
console.log(data)
}
})
es6写法1
const fs = require('fs')
const promisify= require('util').promisify
const readFile=promisify(fs.readFile)
async function test() {
try {
var data=await readFile(__dirname+'/process.js','utf8')
console.log(data)
} catch (e) {
console.error(e)
} finally {
}
}
test()
es6写法2
const fs = require('fs')
const readFile=function (filename,args1) {
return new Promise((resolve,reject)=>{
fs.readFile(filename,args1,(err,data)=>{
if(err) return reject(err)
else{
console.log("读文件")
resolve(data)
}
})
})
}
async function test() {
try {
var data=await readFile(__dirname+'/process.js','utf8')
console.log(data)
} catch (e) {
console.error(e)
} finally {
}
}
test()
网友评论