【问题标题】:Write multiple images to disk using Node.js使用 Node.js 将多个图像写入磁盘
【发布时间】:2019-07-16 21:36:44
【问题描述】:

代码说明:

在第一个 .then() 中,我得到了 10 张图像的数据。 然后使用 for of 循环,我遍历每个单独的图像。在下一行中,我将生成一个不同的路径来将图像保存到 ${count}。

现在是主要部分

我正在使用 axios 通过传入 image.url 来获取图像。在 .then() 中,我得到了响应,并将它传送到我事先生成的路径。

解决是否获取数据并增加计数以在下一次迭代中更改路径。出现错误拒绝

我正在执行 console.log(count++) 来检查我是否正在遍历所有 10 个图像并且我得到了 '1 2 ....10' 输出,这意味着一切都是工作正常。


问题:根据代码,images文件夹中应保存10张图片,名称为'image1, image2 ...image10' .但我得到的只是第一张图片。我究竟做错了什么?是否应该在 for 循环中将内容写入磁盘?

client.search('Steve Angello')
.then(images => {
    let count = 1;

    for(image of images){
        const path1 = path.resolve(__dirname, 'images', `image ${count}.jpg`);
        axios({
            method: 'GET',
            url: image.url,
            responseType: 'stream'
        })
        .then((response) => {
                response.data.pipe(fs.createWriteStream(path1));

                return new Promise( (resolve, reject) => {
                    response.data.on('end', () => {
                        resolve();
                        console.log(count++);
                    })

                    response.data.on('error', (error) => {
                        reject(error);
                    })
                })
            })
        .catch((err) => console.log(err));   
    }

});

Snapshot of the output

【问题讨论】:

标签: javascript node.js asynchronous promise axios


【解决方案1】:

所有图像都保存到名为“image 1.jpg”的文件中(10 次)。您可以通过在调用 axios 之前添加一个 console.log 来确认这一点。

我认为最简单的解决方案是改变你的循环

for(image of images){
    const path1 = path.resolve(__dirname, 'images', `image ${count}.jpg`);

for (count = 0; count < images.length; count++) {
    image = images[i];
    const path1 = path.resolve(__dirname, 'images', `image ${count+1}.jpg`);
    // and any other references to count should be removed

【讨论】:

  • 是的,它奏效了。但我不明白我做错了什么?
  • 在您的原始代码中,count++ 更改了 count 的值,但直到分配了 path1 之后才执行此操作(相同值的 10 次)。由于异步代码的性质,执行顺序不是 axios(), then(), axios(), then()...而是 axios(), axios(), axios(),... then (), 然后(), 然后()...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 2019-03-06
相关资源
最近更新 更多