从可读创建存档,将文件和管道添加到可写
目标是从客户端接收存档、添加文件并将其上传到 Cloud Storage,而不创建临时文件。客户端和服务器都使用archiver
库。下面代码的问题是 file2.txt
没有添加到存档中。
客户端:
import archiver from "archiver";
const archive = archiver("zip", {
zlib: { level: 9 },
});
archive.append("string cheese!", { name: "file1.txt" });
await fetch(`/archive`, {
method: "POST",
body: archive,
});
服务器:
import archiver from "archiver";
import { Storage } from "@google-cloud/storage";
import { Router } from "express";
const router = Router();
const storage = new Storage();
router.post("/", (req, res) => {
const archive = archiver("zip", {
zlib: { level: 9 },
});
const cloudFile = storage.bucket("archives").file("archive.zip");
req.pipe(archive, {
end: false,
});
archive.pipe(cloudFile.createWriteStream());
req.on("end", async () => {
archive.append("string cheese!", { name: "file2.txt" });
archive.finalize();
archive.end();
});
});
The goal is to receive an archive form the client, add a file, and upload it to Cloud Storage without creating a temporary file. The client and the server both use the archiver
library. The problem with the code below is that file2.txt
does not get added to the archive.
Client:
import archiver from "archiver";
const archive = archiver("zip", {
zlib: { level: 9 },
});
archive.append("string cheese!", { name: "file1.txt" });
await fetch(`/archive`, {
method: "POST",
body: archive,
});
Server:
import archiver from "archiver";
import { Storage } from "@google-cloud/storage";
import { Router } from "express";
const router = Router();
const storage = new Storage();
router.post("/", (req, res) => {
const archive = archiver("zip", {
zlib: { level: 9 },
});
const cloudFile = storage.bucket("archives").file("archive.zip");
req.pipe(archive, {
end: false,
});
archive.pipe(cloudFile.createWriteStream());
req.on("end", async () => {
archive.append("string cheese!", { name: "file2.txt" });
archive.finalize();
archive.end();
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如我从 文档 中看到的
他们正在使用 fs.createReadStream(file1) 来访问文件系统
但是,如果您从接收到的数据中获取缓冲区,则可以实现此目的,
如果您在无服务器环境中工作,则很可能您无权访问,这也是一个提示
对文件系统进行读取、写入和清理
但在某些情况下您可以访问 /temp 目录
如果是这种情况,值得快速搜索
as i can see from the documentations
they are using fs.createReadStream(file1) to reach out file system
however you can achieve this if you get Buffer from the received data
also a tip if you working in serverless env most likely you don't have access
to file system to read, write and clean
but at some cases you have access to /temp directory
it worth a quick search if this is the case