Nodejs expresses readfile and returns response asynchronously

I want to do something like this

 router.get('/getforecast/:stationShortCode', function(req,res){
 var stationShortCode = req.params.stationShortCode;

 var fs = require('fs');
 fs.readFile("data/wx.hourly.txt", "utf8", function(err, data){
    if(err) throw err;
     //do operation on data that generates say resultArray;
     return resultArray;
  });

 res.send(resultArray);

});

      

is obviously res.send

called synchronously whereas the file reads async. Is there a sane solution? Am I forced to actually go through res

?

+3


source to share


1 answer


fs.readFile("data/wx.hourly.txt", "utf8", function(err, data){
    if(err) throw err;

    var resultArray = //do operation on data that generates say resultArray;

    res.send(resultArray);
});

      



Your file is being read. The callback that you passed to the function is readFile

called. Then you can generate data and then send a response. Take a look at how asynchronous callbacks work, because here your code is not executing from the top down as you think. And since anonymous functions "remember" all the variables from the scope around them, you can use res inside this callback.

+3


source







All Articles