I am trying to make a simple read file function in my Appjs program. All that is happening is that the Appjs is calling a function inside my app.js
file and running it in node.js. This function then returns a value to my Appjs program by window.returnData = data;
This works, however I can't get it to work in the order I want. The node.js function seems to be running AFTER the Appjs function although it is inside of it.
Here is the function inside of my Appjs index.html
file that starts the entire process.
var returnData;
function r(path,d) {
window.readFromFile(path,d); //call to the function readFromFile below
alert(returnData);
}
readFromFile()
function from the app.js file that Is being called from above
window.readFromFile = function(path,d) {
var fs = require('fs');
if (d == 1) {
path = __dirname + path;
}
fs.readFile(path, {encoding: 'utf-8'}, function(err,data){
if (err){
console.log(err);
} else {
console.log('File read');
window.returnData = data;
}
});
}
Here is my problem. The first call of this function will alert the text undefined
. However, after the alert function, I know that the window.returnData = data;
line above is working because if I create a button to alert the variable returnData
again or I run the readFromFile
function again, it alerts the data correctly.
Am I incorrect in thinking that the child function should complete first? Is there a way around this? I don't want to create a loop that continuously checks for the variable to change.
Thanks in advance.