node读取文件模块util

2018-08-16  本文已影响0人  noyanse
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()



上一篇下一篇

猜你喜欢

热点阅读