美文网首页
用nodejs获取文件内容的方法来区分callback和Prom

用nodejs获取文件内容的方法来区分callback和Prom

作者: 诚实可靠小郎俊 | 来源:发表于2019-11-19 11:39 被阅读0次
先创建src文件夹,src里面创建files文件夹和index.js文件。 files文件夹里面分别创建a.json,b.json,c.json。我是怕自己忘记,做的笔记没有做注释看不懂就算了,我自己看懂就可以了

a.json

{
    "next": "b.json",
    "msg": "this is a.json"
}

b.json

{
    "next": "c.json",
    "msg": "this is b.json"
}

c.json

{
    "next": "null",
    "msg": "this is c.json"
}

index.js callback方式

const fs = require('fs');
const path = require('path');


// callback 方式获取一个文件的内容
function getFileContent(fileName, callback) {
    const fullFileName = path.resolve(__dirname, 'files', fileName)
    fs.readFile(fullFileName, (err, data) => {
        if (err) {
            console.log(err)
            return
        }
        callback(
            JSON.parse(data.toString())
        )
    })
}

// 测试 callback 回调地狱
getFileContent('a.json', aData => {
    console.log('a.json', aData)
    getFileContent(aData.next, bData => {
        console.log('b.json', bData)
        getFileContent(bData.next, cData => {
            console.log('c.json', cData)
        })
    })
})

index.js 用promise方式

const fs = require('fs');
const path = require('path');


// 用promise 获取文件内容
function getFileContent(fileName) {
    const fullFileName = path.resolve(__dirname, 'files', fileName)
    const promise = new Promise((resolve, reject) => {
        fs.readFile(fullFileName, (err, data) => {
            if (err) {
                reject(err)
                return
            }
            resolve(
                JSON.parse(data.toString())
            )
        })
    })
    return promise
}
getFileContent('a.json').then(aData => {
    console.log('a.json', aData)
    return getFileContent(aData.next)
}).then(bData => {
    console.log('b.json', bData)
    return getFileContent(bData.next)
}).then(cData => {
    console.log('c.json', cData)
})

相关文章

网友评论

      本文标题:用nodejs获取文件内容的方法来区分callback和Prom

      本文链接:https://www.haomeiwen.com/subject/ukjwictx.html