使用Deno上传文件至Google Cloud Storage遇兼容问题,求替代方案
Deno上传Google Cloud Storage的替代方案
方案1:直接调用GCS REST API(无需第三方库)
Deno原生支持fetch,可以直接调用Google Cloud Storage的REST API完成文件上传,完全规避Node模块兼容性问题。
步骤示例:
- 准备服务账号密钥文件(JSON格式),提取其中的
private_key和client_email。 - 生成JWT令牌用于认证(推荐服务账号认证,比API密钥更安全)。
- 构造上传请求,用
fetch发送文件内容。
代码示例:
// 读取服务账号密钥 const serviceAccount = await Deno.readTextFile("./service-account-key.json"); const { private_key, client_email } = JSON.parse(serviceAccount); // 生成JWT令牌 import { create } from "https://deno.land/x/djwt@v2.9.1/mod.ts"; const payload = { iss: client_email, scope: "https://www.googleapis.com/auth/devstorage.read_write", aud: "https://oauth2.googleapis.com/token", exp: Math.floor(Date.now() / 1000) + 3600, iat: Math.floor(Date.now() / 1000), }; const jwt = await create({ alg: "RS256", typ: "JWT" }, payload, private_key); // 获取访问令牌 const tokenResponse = await fetch("https://oauth2.googleapis.com/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: jwt, }), }); const { access_token } = await tokenResponse.json(); // 上传文件到GCS const bucketName = "your-bucket-name"; const filePath = "./local-file.txt"; const fileContent = await Deno.readFile(filePath); const gcsObjectName = "uploaded-file.txt"; await fetch(`https://storage.googleapis.com/upload/storage/v1/b/${bucketName}/o?uploadType=media&name=${gcsObjectName}`, { method: "POST", headers: { "Authorization": `Bearer ${access_token}`, "Content-Type": "text/plain", // 根据文件实际类型调整 }, body: fileContent, }); console.log("文件上传成功");
方案2:使用Deno专用的GCS第三方库
有专门为Deno开发的Google Cloud Storage客户端库,完全适配Deno环境,无需处理Node兼容性问题。
使用示例:
// 导入Deno专用GCS库 import { Storage } from "https://deno.land/x/google_storage@v1.1.0/mod.ts"; // 初始化Storage实例 const storage = new Storage({ keyFilename: "./service-account-key.json", // 服务账号密钥文件路径 }); // 获取目标存储桶 const bucket = storage.bucket("your-bucket-name"); // 上传本地文件到GCS await bucket.upload("./local-file.txt", { destination: "uploaded-file.txt", // 指定GCS中存储的文件名 }); console.log("文件上传成功");
方案3:兼容Node模块(不推荐,易出问题)
如果坚持使用@google-cloud/storage,可以启用Deno的Node兼容性模式,但需要额外处理缺失的API:
- 运行脚本时添加不稳定标志:
deno run --unstable --node-modules-dir your-script.ts - 手动polyfill缺失的
crypto.Sign,比如使用@deno/shim-crypto等兼容库,但这种方法容易触发其他兼容性报错,不建议用于生产环境。
内容的提问来源于stack exchange,提问作者avalero
相关产品推荐
相关产品推荐

