2
\$\begingroup\$

I am using node.js with express. There is a button that the user can click, and doing so calls this method on the server:

app.get('/getTime', function(req, res) {
 var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';
 http.get(url + '?key=' + apikey, function(resp) {
 var xml = '';
 resp.on('data', function(chunk) {
 xml += chunk;
 });
 resp.on('end', function() {
 console.log(xml);
 res.send(xml);
 });
 });
});

This works, strictly speaking, in that the client side does receive the XML data. What bothers me is that there are two response objects that I have only dealt with by calling one "res" and the other "resp". I have a feeling I am handling the callbacks the wrong way, or that the entire structure of this task is done incorrectly.

I would appreciate some guidance about the "right way" to do this, as I am sure this is not it.

asked Sep 19, 2014 at 13:28
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Since the HTTP response implements Writable Stream and Express wraps around HTTP, you can pipe the output to the response, like so:

app.get('/getTime', function(req, res) {
 var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';
 http.get(url + '?key=' + apikey, function(incoming) {
 incoming.pipe(res);
 }
});

It will not only cut down on latency times but also cut down on lines of code.

answered Sep 20, 2014 at 4:37
\$\endgroup\$
1
  • \$\begingroup\$ That's excellent, thanks very much. I knew there was something I wasn't quite seeing and this is it. \$\endgroup\$ Commented Sep 20, 2014 at 13:40
0
\$\begingroup\$

From a once over:

  • Your indenting is off, try something like jsbeautifier.org
  • Dont do console.log in production code, it is synchronous and slow
  • Other than that your code is very typical, there is nothing obviously wrong

Furthermore, would this work for you ?

app.get('/getTime', function(req, res) {
 var url = 'http://www.ctabustracker.com/bustime/api/v1/gettime';
 http.get(url + '?key=' + apikey, res);
});

Since you are anyway sending the data thru, I wonder if this would work.

answered Sep 19, 2014 at 20:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.