0

I build this function but it return nothing :

function myFunction(index){
    var resultat = "";
    fs.readFile(__dirname + '/File.xml', function(err, data) {
        parser.parseString(data, function (err, result) {
            resultat = result['level1']['level2']['level3'][index];
            //console.log(resultat); // works
        });
    });
    return resultat;// Return nothing
    // return 'test' // Works
}

Hope you will can help me !

Braiam
  • 1
  • 11
  • 47
  • 78
Anonymous
  • 468
  • 5
  • 26
  • 1
    The `fs.readFile()` operation is *asynchronous*. The result won't be available until the operation finishes. – Pointy Apr 18 '16 at 17:54

1 Answers1

0

Your function returns before your xml call has time to load the remote XML.

Try:

function getItem(index, callback){
    var resultat = "";
    fs.readFile(__dirname + '/SearchRequest.xml', function(err, data) {
        parser.parseString(data, function (err, result) {
            resultat = result['rss']['channel']['item'][index];
            //console.log(resultat); // works
            callback(resultat);
        });
    });
}

var index = 1;
getItem(index, function(d){
  console.log(d);
});
Radio
  • 2,810
  • 1
  • 21
  • 43