如何在node.js中逐行执行并发限制
我试图逐行阅读一个文件,并使用读取的数据做一些asynchronousfunction。 我需要限制这个并发。 我知道如何逐行阅读,如何使用模块来完成并发,但我不知道如何把它们放在一起。 我正在使用逐行和喉咙模块。
这是我迄今为止尝试没有成功的:
// modules const CONCURRENCY = 5 const throat = require('throat')(CONCURRENCY) const LineByLineReader = require('line-by-line') lr = new LineByLineReader('urls.txt') throat(() => { lr.on('line', function (line) { return main(line) // this is an async function that returns a promise Promise.resolve() }) })
你需要使用line
callback里面的throat
const CONCURRENCY = 5 const throat = require('throat') const LineByLineReader = require('line-by-line') lr = new LineByLineReader('urls.txt') lr.on('line', throat(CONCURRENCY, main))
此外,您可以使用节点的内置readline模块,而不是line-by-line
:
const fs = require('fs') const readline = require('readline') readline. createInterface({input: fs.createReadStream('urls.txt')}). on('line', throat(CONCURRENCY, main))