Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs express read file and return 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);

});

obviously, res.send is called synchronously, whereas the file reads async. Is there a clever solution to this? Am I forced to actually pass in res?

like image 951
Toskan Avatar asked Jul 31 '15 05:07

Toskan


People also ask

How do I read a node JS asynchronous file?

The fs. readFileSync() method is an inbuilt application programming interface of fs module which is used to read the file and return its content. In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs.

Is Expressjs asynchronous?

Your handler is 100% synchronous. The engine will only run one of them at a time.

What does Express () method do?

Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.

Can we send HTML file as response in Express?

js and Express applications, res. sendFile() can be used to deliver files. Delivering HTML files using Express can be useful when you need a solution for serving static pages.


1 Answers

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 read. The callback you passed to the readFile function is called. Then you can generate the data, and then you can send the response. Look into how asynchronous callbacks work, because here your code is not executed from top to bottom like you think it is. And because anonymous functions "remember" all the variables from the scope around them, you can use res inside that callback.

like image 65
ralh Avatar answered Nov 10 '22 03:11

ralh