You need to enable JavaScript to run this app. NodeJS基于@google-cloud/storage下载GCS指定路径文件出现0B大小异常
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS基于@google-cloud/storage下载GCS指定路径文件出现0B大小异常

问题复现与环境说明
  • 业务目标:持有entryIdsWithImages数组,数组元素对应GCS中的类文件夹路径标识,需要从这些指定GCP路径下下载全部图片,将文件存储到临时目录后打包为压缩包。
  • 异常表现:参考@google-cloud/storage的getFiles方法实现下载逻辑后,运行生成的图片文件大小为0B,对应文件在GCS上的实际存储大小完全正常。
  • 版本验证:在@google-cloud/storage@^4.7.0版本下可复现问题,升级到库的最新版本后问题依旧存在。
  • 原实现代码:
await Promise.all(
    entryIdsWithImages.map(async (entryId) => {
        const prefix = `images/${uid}/${entryId}`;
        // 下载对应entryId关联的图片
        const [files] = await bucket.getFiles({
        prefix,
        });
        files.forEach(async (file) => {
            // file.name包含文件完整路径,提取最内层文件名作为本地存储文件名
            const fileName = file.name.slice(
                file.name.lastIndexOf('/') + 1
            );
            const imgTempFilePath = path.join(imageDirectory, fileName);
            try {
                await file.download({
                destination: `${imgTempFilePath}.jpg`,
                });
            } catch (e) {
                console.log(
                `Error downloading the image at ${prefix}/${fileName}: `,
                e
                );
            }
        });
    })
)
问题核心根因
  • 异步流程未被正确等待,是生成0B文件的直接原因:Array.forEach方法不会收集入参async回调返回的Promise,外层的Promise.all根本感知不到内层的文件下载任务正在执行。主流程走完会直接进入后续的压缩包打包、甚至进程退出流程,此时文件下载的写入流还未完成,操作系统会将未写完的文件截断为0B大小。
  • 逻辑冗余问题:下载目标路径硬编码拼接了.jpg后缀,和从文件路径提取的原始文件名不匹配,会导致非jpg格式的文件(如png、webp)文件类型错乱。
修复方案
  1. 替换不支持异步等待的forEach逻辑,用Promise.all包裹单个文件的下载任务,确保当前路径下的所有文件全部下载完成后,主流程才会继续执行。
  2. 移除硬编码的.jpg后缀,直接使用提取的原始文件名作为下载目标路径,避免文件类型错乱。
  3. 提前创建临时存储目录,避免因目录不存在导致的下载失败。

修复后的可运行代码示例:

const path = require('path');
const fs = require('fs/promises');

// 提前递归创建临时图片目录,避免下载时找不到路径
await fs.mkdir(imageDirectory, { recursive: true });

await Promise.all(
  entryIdsWithImages.map(async (entryId) => {
    const prefix = `images/${uid}/${entryId}`;
    // 检索指定前缀下的所有文件
    const [files] = await bucket.getFiles({ prefix });
    // 等待当前entryId路径下所有文件的下载任务全部完成
    await Promise.all(
      files.map(async (file) => {
        // 提取文件的原始名称
        const fileName = file.name.slice(file.name.lastIndexOf('/') + 1);
        const imgTempFilePath = path.join(imageDirectory, fileName);
        try {
          await file.download({
            destination: imgTempFilePath,
          });
        } catch (e) {
          console.log(`Error downloading the image at ${prefix}/${fileName}: `, e);
        }
      })
    );
  })
);
排坑提示
  • Node.js中所有涉及文件IO的异步操作,都必须被正确await,否则主流程退出时未完成的文件写入会被直接截断,生成大小为0B的无效文件。
  • 不要使用forEach处理需要等待完成的异步任务,这类场景下优先用map收集所有Promise后用Promise.all统一等待。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 03:24:06