Abhinav Abhinav - 3 months ago 17
JSON Question

nodejs - prints undefined on calling function in another js file

I am getting below error on executing code below :

Failed: path must be a string
Stack:
TypeError: path must be a string
at TypeError (native)
at Object.fs.readFile (fs.js:250:11)


The code being ran is as below:

this.getNodeValueFromXML = function(xmlPath,node){
var self = this;
try {
var file = path.join(__dirname, xmlPath)
fs.readFile(file, function(err, data) {
if(err){
logger.warnLogger(err,'Error while processing XML file!!');
}
else{
parser.parseString(data, function (err, result) {
if(err){
logger.warnLogger(err,'Not a valid file!!');
}
else {
var value=self.getValueFromJson(result,node);
return value;
}
});
}
});
}
catch(e){
if (e.code !== 'ENOENT') {
throw e
} else {
logger.warnLogger(e,'File not found!');
}
}
};


I am calling this
function
from other js file using below syntax

commonFunction.getNodeValueFromXML("../my.xml",'user.name');


Earlier it was giving error
Failed: path must be a string Stack:
. After making the changes as
path.join(__dirname, xmlPath)
, it works but calling same function from another
js
file prints undefined.

Can someone help

Answer

use path.join(__dirname, '../my.xml') for solving below issue:

Failed: path must be a string
Stack:
  TypeError: path must be a string
      at TypeError (native)
      at Object.fs.readFile (fs.js:250:11)

For calling function from another file I modified code to use callback function.

Comments