【问题标题】:Fetch images and upload to Google Cloud Storage获取图片并上传到 Google Cloud Storage
【发布时间】:2020-04-08 19:09:30
【问题描述】:

我正在尝试将给定的结果(图片的 URL)下载到谷歌云存储。 代码在 firebase 函数中运行,由 pub/sub 触发。
使用 unsplash API 的一切工作正常,for 循环也在循环,但它不会将图像保存到云存储或抛出任何错误。我不知道可能是什么问题。

 // Search Photos on Unsplash
      unsplash.search.photos('searchTerm', 1, 5, { orientation: "landscape" })
      .then(toJson)
      .then(async res => {

        const images = res.results;

            for (const image of images) {
              await fetch(image.urls.raw)
                .then(result => {

                  // The Part that is not working
                  result.body.pipe(storage.bucket('bucket-id.appspot.com/').file(image.id+".jpg").createWriteStream());

                  return true;
                });
              } 
          });

【问题讨论】:

  • 你试过用upload()代替createWriteStream吗?

标签: node.js async-await google-cloud-functions google-cloud-storage firebase-storage


【解决方案1】:

有两种可能的原因:

  • 来自createWriteStream()WritableStream 未正确关闭。
  • 您的云功能即将终止。

通常,ReadableStream.pipe() 默认会为您关闭流 - 只要没有错误。在管道过程中遇到错误时,目标永远不会关闭。

为了帮助调试,将错误侦听器附加到 ReadableStream 并查看它是否在抱怨什么:

result.body.on('error', (err) => console.log('Encountered an error while piping file: ', err));

除了潜在的未捕获错误之外,使用 body.pipe() 是一个异步操作,但您的函数处理程序会立即返回 true,表明您的云函数可以终止。

要解决这个问题,请将 body.pipe() 包装在 Promise 中。您还可以从上面链接错误处理程序以拒绝承诺。

return new Promise((resolve, reject) => {
  const readStream = result.body;
  const writeStream = storage.bucket('bucket-id.appspot.com/').file(image.id+".jpg").createWriteStream();

  readStream.on('error', reject);
  writeStream.on('error', reject); // may as well connect it
  writeStream.on('finish', () => resolve(true)); // fired by pipe() when it's done

  readStream.pipe(writeStream);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2015-02-21
    • 2020-07-26
    • 2017-08-11
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    相关资源
    最近更新 更多