12

I am learning node under workshops from nodeschool. name of workshop is learnyounode, question number 8. HTTP COLLECT.

Question was: Write a program that performs an HTTP GET request to a URL provided to you as the first command-line argument. Collect all data from the server (not just the first "data" event) and then write two lines to the console (stdout). The first line you write should just be an integer representing the number of characters received from the server. The second line should contain the complete String of characters sent by the server.

The answer i submitted was as follows.

var http = require('http');
var url = process.argv[2];
http.get(url,function(res){
    var body = '';
    res.on('error',function(err){
        console.error(err);
    })
    res.on('data',function(chunk){
        body+=chunk.toString();
    });
    res.on('end',function(){
        console.log(body.length);
        console.log(body);
    });
});

while the answer they provided was,

var http = require('http')
var bl = require('bl')
http.get(process.argv[2], function (response) {
  response.pipe(bl(function (err, data) {
    if (err)
      return console.error(err)
    data = data.toString()
    console.log(data.length)
    console.log(data)
  }))
})


I would like to know the difference between these two codes. and please explain how http.get() and pipe works ...

1
  • Please provide their question here, too Commented Jun 18, 2016 at 18:56

1 Answer 1

15

The only difference is how you two handled the response. You handled the response chunk by chunk and appended the string equivalent to body. They used pipe to send a readable stream response and send it to a writable stream bl (buffer list) which can wait until the readable stream is done before proceeding. While you subscribed to the emitter of 'data' to handle the response chunks, bl does that under the covers.

pipe is a function called on a readable stream that is passed a parameter of a writable stream.

Edit: I just noticed the date of your post. It's odd no one answered this...

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

2 Comments

Even with your late response, 3 years later I'm searching for this being happy someone wrote a good answer describing the differences :).
And here I am, finding this great answer 7 years later! (+1)

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.