[英]How to get files from URLs in nodeJS, build a zip file and pipe to cloud storage bucket
我想构建一个接收 object 的云 function,如下所示:
{
"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"
}
I would like to get those files, compress them into a zip file (with name = referenceId), save that zip file to a bucket, and finally, send the zip URL back as a response.
我的主要问题在于使用 memory 以及我希望正确使用管道/流。 我真的很感激在哪里可以找到这个实现的文档的好资源。
这是我现在得到的,但我不知道它是否有好处:
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);
};
编辑:这个问题似乎有很多问题。 但由于这必须作为一个单一的 stream 工作,我要求的不是确切的答案,而是关于研究什么以更好地理解解决方案的想法。
您收到“未处理的拒绝 TypeError: dest.write is not a function” bc ourBucket
is not a writable stream 。 它必须是可写的 stream 的实例,您可以将 pipe 写入它。 您应该创建一个可写的存储桶文件 stream并将其用作ourBucket
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.