我正在尝试写入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
}
答案 0 :(得分:-2)
return str
在readFile
回调中,您应该使用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)
})
Here is some information on async functions
希望这会有所帮助。