last day (15 days later) » 

8:27 PM
-1
A: Not able to read JSON file after writing to the same JSON file

anbcodesThe return str is inside of the readFile callback you should either use async and await or use fs.readFileSync like this: function readJson() { let data = fs.readFileSync(json_file) let iplist = data.toString() iplist = JSON.parse(iplist) let str = JSON.stringify(iplist) retu...

 
Thank your for your response. However, I think there is an error in your answer. Is fs.readFileSync(json_file) not suppose to have a callback where I can access data?
 
@ApplePie The data is returned from fs.readFileSync().
 
I am trying to use the async way and I am getting undefined when I try to do readJson().then((result) => { console.log(result) })
 
@ApplePie Does the readFileSync() way work?
 
yes, it does. But the async way does not though. I am really trying to understand how to make it work using async/await
 
8:27 PM
You could try logging str right before the return.
I moved it to chat
 
Hi
Thank you for your time and help
 
Your welcome
 
I did some research and realize that overuse of synchronous methods might actually affect my node application. Hence, I am trying to use the async/await way to read and write files
 
Ok, so you said it is logging undefined. Did you try logging str right before return str?
 
before the "return str" it does show
 
8:37 PM
Ok so I just found out fs.readFile() does not return a promise (stackoverflow.com/questions/41203409/…)
But I will fix it
 
I have attached a screenshot for I hav currently have. I really appreciate your help.
I find it a bit hard to understand asycn/await and their combination with try{}catch(){}
 
I updated my answer.
Did my updated answer work?
 

last day (15 days later) »