写入相同的JSON文件后无法读取JSON文件

时间:2019-06-20 18:58:26

标签: javascript node.js express

我正在尝试写入json文件,在该文件写入后,我将再次重新读取该文件。但是,当我尝试重新读取文件时,我的console.log(readJson());向我显示undefined。谁能建议我该怎么做?

helper.js

const fs = require('fs')
const util = require('util');
const path = require('path')
const json_file = path.resolve(__dirname, "../json/metrics.json")



function readJson(){
    fs.readFile(json_file,function(err,data){
        if(err){
            return console.error(err)
        }
        let iplist = data.toString()
        iplist = JSON.parse(iplist)
        let str = JSON.stringify(iplist)
        return str
    })
}

function writeJson(ipdetails){

    fs.readFile(json_file,function(err,data){
        if(err){
            return console.error(err)
        }
        let iplist = data.toString()
        iplist = JSON.parse(iplist)
        iplist.table.push(ipdetails.data)
        let str = JSON.stringify(iplist)
        fs.writeFile(json_file,str,function(err){
            if(err){
                console.error(err);
            }
            console.log('returning readJson() below')
            console.log(readJson());
        })
    })
}


module.exports = {
    writeJson,
    readJson
}

1 个答案:

答案 0 :(得分:-2)

return strreadFile回调中,您应该使用promise或fs.readFileSync,如下所示:

function readJson() {
    let data = fs.readFileSync(json_file)
    let iplist = data.toString()
    iplist = JSON.parse(iplist)
    let str = JSON.stringify(iplist)
    return str
}

异步方式会更困难:

function readJson() {
    new Promise((resolve, reject) =>
        fs.readFile(json_file, type, (err, data) => {
          let iplist = data.toString()
          iplist = JSON.parse(iplist)
          let str = JSON.stringify(iplist)
          return err ? reject(err) : resolve(str);
        })
    );
}

您这样称呼异步版本:

readJson().then((result) => {
  console.log(result)
})

async file example

Here is some information on async functions

希望这会有所帮助。