Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using async.js with node.js streams

I want to use asyn.js for limiting the number of parallel io operations. I have come across the following example:

async.forEachLimit items, 5, ((item, next) ->
  request item.url, (error, response, body) ->
    console.log body
    next error)
    , (err) ->
        throw err  if err
        console.log "All requests processed!"

But I want to use it with streams, like this:

async.forEachLimit items, 5, ((item, next)->
    stream = fs.createWriteStream file
    request.get(item.url).pipe(stream))
    , (err)->
          throw err  if err
          console.log "All requests processed!"

How do I place the 'next' call when the writestream is done writing to file?

like image 988
tldr Avatar asked Aug 13 '26 14:08

tldr


1 Answers

You'll need to bind to the Readable Stream's 'end' event separate from the .pipe().

res = request.get(item.url)
res.pipe(stream)
res.on 'end', next

This also lets you bind to its 'error' event:

res.on 'error', next

But, you could also listen to the Writable Stream's 'finish' event:

request.get(item.url)
    .on 'finish', next
like image 113
Jonathan Lonowski Avatar answered Aug 16 '26 09:08

Jonathan Lonowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!