I have this function which I use to extract a string value from an xml and then convert to a float. It is as follows
function stringtoFloat() {
var parser = new xml2js.Parser();
fs.readFile('C:\\Temp\\tasks\\acis\\110-1100.sat\\110-1100.sat.response.xml', function (err, data) {
parser.parseString(data, function (err, result) {
var timeString = result.Message.Response[0].Events[0].MessageReportEvent[8].$.Message;
var fileTime = timeString.substr(13, 20);
var filetimeVal = parseFloat(fileTime);
return filetimeVal;
});
});
};
Then I run this function 5 times to sum up the values from each of those runs
function funcTotal() {
var sum = 0;
for (itr = 1; itr <= 5; itr++) {
var numFunc = stringtoFloat(); //store the output from the function in a variable
sum = sum + numFunc; //Get the sum of all 5 variables
}
console.log(sum);
return sum;
}
funcTotal();
When I run this I get the result as 'NaN' Why is this? and how do I resolve this?
I have updated the code by replacing fs.readFile
with fs.readFileSync
in the following manner.
function parseTime(){
var parser = new xml2js.Parser();
var data = fs.readFileSync('C:\\Temp\\tasks\\acis\\110-1100.sat\\110-1100.sat.response.xml', {encoding:'utf8'});
parser.parseString(data, function (err, result) {
var timeString = result.Message.Response[0].Events[0].MessageReportEvent[8].$.Message;
var fileTime = timeString.substr(13,20);
var filetimeVal = parseFloat(fileTime);
console.log(filetimeVal);
return filetimeVal;
});
};
Apparently half of the problem is resolved. It seems the funcTotal() runs after stringtoFloat now, unlike before. But still I get NaN. Can you please help?