0

I'm starting to use NodeJs recently and I'm trying to create a API that will get some information from web compile it and show to the user.

My question is the follow

router.get('/', function (req, res, next) {
  https.get(pageUrl, function (res) {
     res.on('data', function (responseBuffer) {
         //Important info;
        info = responseBuffer;
     }
   }

   res.render('page', { important: info});
 }

How can I wait until I have the "info" var and then send the res.render. Because right now if I try to wait it usually the program ends and don't wait the result.

Thanks.

Carlos EduardoL
  • 670
  • 6
  • 14

1 Answers1

4

Assuming your https.get call gives you a stream with an 'end' event [1], you can do the following:

router.get('/', function (req, res, next) {
  https.get(pageUrl, function (res) {
     var info;

     res.on('data', function (responseBuffer) {
         //Important info;
        info = responseBuffer;
     }

     res.on('end', function() {
       res.render('page', { important: info});
     })
   }
 }

Note that the above code will not work because you shadowed the base res parameter with the res parameter from the https.get callback.

Also, note that the 'data' event may be emitted several times (again, assuming a standard stream implementation[1]), so you should accumulate the results inside your info variable.

[1] Could you please post more information about your code, such as where the https library comes from (is it the standard HTTPS lib?).


Personal thought: I highly suggest using the request module, disponible on NPM via npm install request, for HTTP(S) requests to external services. It's got a neat interface, is simple to use and handles a lot of situations for you (redirects are one example, JSON and Content-Type another).

Pampattitude
  • 456
  • 2
  • 10