1

I am trying to push the result obtained from a URL using http into an array. Following is the code:

var bl = require('bl')
var http = require('http')
var contents = []
var urls = process.argv.slice(2)

urls.forEach((url) => {
http.get(url, (res) => {
    res.setEncoding('utf-8')
    res.pipe(bl((err, data) => {
        if(err)
            return console.error(err)
        else
            contents.push(data.toString())
    }))
})
})

contents.forEach( (con) => {
    console.log(con)
})

But for some reason I get an empty 'contents' array. Any help?

Farhat Nawaz
  • 202
  • 5
  • 20
  • 1
    It's because `get` is asynchronous. `contents.forEach( (con) => { ... });` get executed before `get` recieve anything, that's why the array show up empty in the console. Wrap the code in a function and call that function when `get`'s callback get executed, or just put the code inside `get`'s callback (after you do the `push`ing). – ibrahim mahrir Jul 16 '17 at 16:27

0 Answers0