You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中通过gs:// URI下载Google Cloud Storage对象

Node.js 从gs:// URI获取GCS文件实例的方法

你不需要手动解析gs://格式的URI,@google-cloud/storage SDK 2.5.0及以上版本已经内置了直接从URI获取File实例的原生方法,使用方式如下:

const { Storage } = require('@google-cloud/storage');
const storage = new Storage();

// 直接传入gs格式URI即可拿到对应文件实例
const gcsFileUri = 'gs://你的存储桶名称/文件路径/目标文件';
const file = storage.fileFromURI(gcsFileUri);

// 后续下载逻辑和官方示例完全一致
async function downloadToLocal(localSavePath) {
  await file.download({
    destination: localSavePath
  });
  console.log('文件下载完成');
}

如果你使用的是旧版本SDK,没有内置fileFromURI方法,可以用简单的字符串拆分手动解析URI:

// 自定义解析gs URI的方法
function parseGsUri(uri) {
  if (!uri.startsWith('gs://')) {
    throw new Error('输入不是合法的GCS URI');
  }
  // 去掉前缀后拆分存储桶名称和文件路径
  const [bucketName, ...pathSegments] = uri.slice(5).split('/');
  const filePath = pathSegments.join('/');
  return { bucketName, filePath };
}

// 使用示例
const { bucketName, filePath } = parseGsUri('gs://my-bucket/my-file');
const file = storage.bucket(bucketName).file(filePath);

注意事项

  • 解析指向存储桶根目录的URI时,得到的filePath会是空字符串,对应存储桶根位置
  • 请确保你的运行环境已经配置了对应GCS资源的访问权限,避免出现权限报错

内容的提问来源于stack exchange,提问作者sffc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:45:02