const fs = require('fs')
fs.readFile('./package.json',(err,data) => {
if(err) return console.log(err)
data = JSON.parse(data)
console.log(data.name)
})
//---------------------------------------------------------
function readFileAsync(path) {
return new Promise((resolve,reject) => {
fs.readFile(path,(err,data) => {
if(err) reject(err)
resolve(data)
})
})
}
//promise-----------------------------------------------
readFileAsync('./package.json').then((data) => {
data = JSON.parse(data)
console.log(data)
})
.catch(err => {
console.log(err)
})
//async-----------------------------------------------
async function start() {
let data = await readFileAsync('./package.json')
console.log(JSON.parse(data))
}
start()
//util--------node8才有的-------------------------------------------
const util = require('util')
util.promisify(fs.readFile)('./package.json')
.then(JSON.parse)
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
})
//async-------promisify----------------------------------------
const fs = require('fs')
const util = require('util')
const readAsync = util.promisify(fs.readFile)
async function init () {
try {
let data = await readAsync('./package.json')
data = JSON.parse(data)
console.log(data)
} catch (err) {
console.log(err)
}
}
init()
网友评论