我正在迭代获得的uri数组,我想知道如何在成功编写图像文件时正确控制这些流,并且只接收max
中指定的图像数量?不知何故,这仍然无视计数。
概要
修改
var count = 1;
var max = 1000;
images.each(function (index, element) {
var uri = element.attribs.src;
request(uri).pipe(fs.createWriteStream(output(uri)))
.on('data', function () {
console.log('[' + chalk.green('+') + ']' + ' wrote image ' + count);
sleep.sleep(1); // pause between requests
});
.on('end', function () {
count++;
if (count === max) {
process.exit(0);
}
});
.on('error', function () {
console.log('[' + chalk.red('x') + ']' + ' failed to write image');
});
});
答案 0 :(得分:0)
这是一个可能的解决方案:
var left = 1000,
imagesChunk = images.slice(0, left);
function onDone() {
// we're done!
}
left = imagesChunk.length;
imagesChunk.each(function (index, element) {
var uri = element.attribs.src;
var stream = request(uri);
var writeStream = fs.createWriteStream(output(uri));
var hadError = false;
stream.on('error', function(err) {
if (hadError)
return;
console.log('[' + chalk.red('✗') + ']');
writeStream.close();
hadError = true;
})
.pipe(writeStream)
.on('error', function(err) {
if (hadError)
return;
console.log('[' + chalk.red('✗') + ']');
stream.destroy();
hadError = true;
})
.on('close', function() {
if (!hadError)
console.log('[' + chalk.green('✓') + ']');
if (--left === 0)
onDone();
});
});