I'm writing an electron app that requires me to read from a file and parse its contents into a javascript object using jQuery, and I've been having trouble. At the moment myObject (see in code) is returning null, when it should be returning a live javascript object parsed from the json file. The code I'm using is below and may be worth pointing out that it is written in a renderer process. I'm pretty new to javascript so it could well be something obvious I'm missing.
loadObjectBtn.addEventListener('click', function loadObject(event){
myObject = jsonParser('C:\\someFolder\\myApp\\myJsonFile.json')
console.log(myObject)
return myObject
})
function jsonParser(fileName){
var jsonObj = null
fs.readFile(fileName, 'utf8', function (err,data){
if(err){
return console.log(err)
}
console.log("read from file successfully")
jsonObj = jQuery.parseJSON(data)
})
return jsonObj
}
Interestingly if I run the code with a break point on the line:
return jsonObj
in the function jsonParser()
, the code seems to work and returns a proper value for myObject
. Do any of you guys know why this might be, or have a suggestion for some alternative code?
Thanks for reading!