如何从 nodeJS 中的 URL 获取文件,构建一个 zip 文件并通过管道传输到云存储桶

How to get files from URLs in nodeJS, build a zip file and pipe to cloud storage bucket

我想构建一个云函数来接收像这样的对象:

{
    "files": [
        {
            "url": "https://myUrl/cat.jpg",
            "name": "cat.jpg"
        },
        {
            "url": "https://anyOtherUrl/mouse.jpg",
            "name": "mouse.jpg"
        },
        {
            "url": "https://myUrl2/dog.jpg",
            "name": "dog.jpg"
        }
    ],
    "referenceId": "cute-images"
}

我想获取这些文件,将它们压缩成一个 zip 文件(名称 = referenceId),将该 zip 文件保存到一个存储桶中,最后,将 zip URL 作为响应发回。

我的主要问题在于内存的使用以及我希望正确使用 pipes/streams。如果能找到此实现的文档,我将不胜感激。

这是我目前得到的,但我不知道它是否有用:

const ZipStream = require("zip-stream");
const fetch = require("node-fetch");
const { Storage } = require("@google-cloud/storage");

exports.zipBuilder = async (req, res) => {

  // Deleted lines of request validation

  let zip = new ZipStream();
  const queue = req.body.files;

  async function addFilesToZip() {
    let elem = queue.shift();
    const response = await fetch(elem.url);
    const stream = await response.buffer();
    zip.entry(stream, { name: elem.name }, (err) => {
      if (err) throw err;
      if (queue.length > 0) addNextFile();
      else zip.finalize();
    });
  }

  await addFilesToZip();

  const storage = new Storage();
  
  const ourBucket = storage.bucket(process.env.DESTINATION_BUCKET);

  zip.pipe(ourBucket); // this fails

  // Get ZIP URL from bucket

  res.send(zipUrl);
};

编辑:这个问题好像很多问题合而为一。但由于这必须作为一个单一的流来工作,我要求的不是确切的答案,而是关于研究什么以更好地理解解决方案的想法。

你得到 'Unhandled rejection TypeError: dest.write is not a function' bc ourBucket is not a writable stream. It must be an instance of writable stream for you to pipe to it. You should create a bucket file writable stream 并将其用作 ourBucket.