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.

\$\endgroup\$
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.

\$\endgroup\$
  • \$\begingroup\$ That's excellent, thanks very much. I knew there was something I wasn't quite seeing and this is it. \$\endgroup\$ – Will Sep 20 '14 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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.