0

I was following this tutorial when a wild step 9 appears.

This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get(). However, this time you will be provided with three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the URLs and print it to the console (stdout). You don't need to print out the length, just the data as a String; one line per URL. The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments.

My code was (It doesn't work fine just when he pleases):

http = require("http");
var url = [process.argv[2], process.argv[3], process.argv[4]];
var responses = [];
var completed_responses = 0;

for(var i in url){
    http.get(url[i], function(response){
        var content = "";
        //if(completed_responses == url.length){
                response.setEncoding("utf-8");
                response.on("data", function(data){
                    content += data;
                })
                response.on("error", console.error);
                response.on("end", function(end){
                    console.log(content);
                });
        
    })
}

And the answer was:

var http = require("http");
var bl = require("bl");
var results = [];
var count = 0;

function printResults(){
    for(var i = 0; i < 3; i++)
        console.log(results[i]);
}

function httpGet(index){
    http.get(process.argv[2 + index], function(response){
        response.pipe(bl(function(err, data){
            if (err)
                return console.error(err);
            
            results[index] = data.toString();
            count++;
            
            if(count == 3)
                printResults()
        }))
    })
}

for(var i = 0; i < 3; i++)
    httpGet(i);

What is the right answer WITHOUT BL/AFTER/ETC?

Thanks to all!

Community
  • 1
  • 1

3 Answers3

0

I've done that tutorial myself when I was first learning node and I remember that step of the tutorial. The solution was fairly underwhelming. Anyway, for your answer:

NodeJs Asynchronous programming - Coordinating parallel calls

You can check the code in the question and make the fixes I suggested in my answer. That should solve it without BL/Async/Whatever else that tutorial mentions.

Community
  • 1
  • 1
ardilgulez
  • 1,856
  • 18
  • 19
0

Here is my code for the Juggling Async challenge without using any third-party libraries.

var http = require("http");
var urls = [process.argv[2], process.argv[3], process.argv[4]];

var urlResults = new Array("", "", "");
var allDoneCount = 0;

urls.forEach(function (_url) {

    http.get(_url, function (resp) {
        resp.on("data", function (data) {
            if (_url === urls[0]) {
                urlResults[0] += data.toString();
            } else if (_url === urls[1]) {
                urlResults[1] += data.toString();
            } else {
                urlResults[2] += data.toString();
            }
        })

        resp.on("end", function () {
            allDoneCount++;
            if (allDoneCount === 3) {
                console.log(urlResults[0]);
                console.log(urlResults[1]);
                console.log(urlResults[2]);
            }
        })

        resp.on("error", function (err) {
            console.log(err);
        })

    }).on("error", function (err) {
        console.log(err);
    })
})
0

This is how you can do it without any external modules(except http ;P).

const http = require('http'); //http module

let results = ["", "", ""]; //this will store the data from http.get()
let counter = 0; //to keep a counter for no of httpget's done

//it will iterate when counter is 3 i.e. the 'end' for all
function print() {
  for (let i = 0; i < 3; i++) {
    console.log(results[i]);
  }
}

//accept index(for process.argv) as parameter
function httpGetter(i) {
  //http.get method on the url first encountered, 2+i because 2 values are reserved
  http.get(process.argv[2 + i], (res) => {
    //for converting (res)ponse to string/alternatively toString() method can be used
    res.setEncoding('utf8');
    //event data on the url, callback with recived chunk as parameter
    res.on('data', function(chunk) {
      //appending the recived chunk to that element of results corresponding to 'i' of httpGetter function
      results[i] += chunk;
    });
    //event end, when no more data is read
    //runs every time for each value of 'i' that is for each url
    res.on('end', function() {
      //to keep count
      counter++;
      //when 3 that is when data from all inputs receved
      if (counter === 3) {
        //print function simply iterating over results array
        print();
      }
    });
  })
}


//inputs are recieved from here
for (let i = 0; i < 3; i++) {
  //i can be index for results
  httpGetter(i);
}