将async.js与node.js流一起使用
我想使用asyn.js来限制并行io操作的数量。我遇到了以下例子:将async.js与node.js流一起使用,node.js,asynchronous,stream,coffeescript,pipe,Node.js,Asynchronous,Stream,Coffeescript,Pipe,我想使用asyn.js来限制并行io操作的数量。我遇到了以下例子: 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 pr
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!"
但我想将其用于流,如下所示:
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!"
writestream写入文件后,如何放置“next”调用?您需要绑定到与
.pipe()
分离的可读流
这还允许您绑定到其“错误”
事件:
res.on 'error', next
但是,您也可以收听可写流的:
这就是我如此爱你的原因。非常感谢你!快速提问。我是否应该在可写流上侦听finish事件,因为它紧跟在可读流之后?如果我在可读流上侦听end事件,我可能会在writestream完成之前调用“next”。@tldr是的,这是可能的。可写流可以缓冲,因此可读流首先结束。所以,
'finish'
可能会更好。不过,对于'error'
事件,您仍然需要res
。
res.on 'error', next
request.get(item.url)
.on 'finish', next