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.

2
  • Put the res.render inside the res.on callback, right beneath the info assignment Commented Dec 8, 2015 at 0:18
  • @Michael, can you explain a little bit more your solution? tymeJV I did tried it, but without success. Commented Dec 8, 2015 at 9:25

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

That's helped a lot. I did follow your advice and start to use the request library, that's was a very good idea too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.