Abhinav
Abhinav

Reputation: 1027

nodejs : TypeError: callback is not a function

I have written below code to read a xml and return a hashmap:

this.xmlObjectRepositoryLoader = function (xmlPath, callback){
        var map = {}
        var innerMap = {};
        var el;
        fs.readFile(xmlPath, "utf-8",function(err, data) {
            if(err){
                console.log('File not found!!')
            }
            else{
                console.log(data)
                var doc = domparser.parseFromString(data,"text/xml");
                var els = doc.getElementsByTagName("Child");
                for(var i =0 ; i< els .length;i++){
                    var e = elements[i];
                    eName = e.getAttribute("a");
                    var params = elm.getElementsByTagName("abc");
                    innerMap = {};
                    for(var j =0 ; j< params.length;j++){
                        var param = params[j];
                        var b = param.getAttribute("b");
                        var c= param.getAttribute("c");
                        innerMap[b] = c;
                    }
                    map[el] = innerMap;
                    innerMap={};
                };
            }
            console.log(map);
            return callback(map);
        });        
    };

And I am calling xmlObjectRepositoryLoader from below method but it returns error as TypeError: callback is not a function:

this.objectLoader = function(filePath){
        if (filePath.includes(".xml")) {
            console.log(this.xmlObjectRepositoryLoader(filePath));
    }

Can you please let me know where I am wrong and how can I resolve this

Upvotes: 3

Views: 20585

Answers (2)

Pabdev
Pabdev

Reputation: 416

Since I dont have the reputation to comment. I am putting in this in answer. Sorry for that. U missed the parameter in the code below

this.objectLoader = function(filePath){
        if (filePath.includes(".xml")) {
            console.log(this.xmlObjectRepositoryLoader(filePath));
    }

this.xmlObjectRepositoryLoader(filePath)

in the above line.

And u can include a validation in the function xmlObjectRepositoryLoader to check whether callback is a function or not and then call it to avoid the error thrown (if its not a mandatory parameter).

Upvotes: 3

Cerbrus
Cerbrus

Reputation: 72957

You're trying to call callback, here:

return callback(map);

However, you're not passing a callback to xmlObjectRepositoryLoader:

console.log(this.xmlObjectRepositoryLoader(filePath));

Do this instead:

this.xmlObjectRepositoryLoader(filePath, function(map){ 
    console.log(map)
});

Upvotes: 7

Related Questions