Google Cloud Storage用zip-bucket压缩时报错:Cannot read properties of null (reading 'length')
问题:GCS文件夹压缩至同存储桶时报错TypeError: 无法读取null的属性(读取'length')
代码示例
import { Storage, File, Bucket } from '@google-cloud/storage'; const Zip = require('zip-bucket'); const storage = new Storage(); const bucket = storage.bucket('bucket_name'); const zipper = Zip(storage); const zipResult = await zipper({ fromBucket: 'bucket_name', fromPath: `folder_name/`, toBucket: 'bucket_name', toPath: `new_file_name.zip`, });
需求说明
目标存储桶与源存储桶为同一存储桶,需将Google Cloud Storage中指定文件夹内的所有文件压缩,并将生成的压缩包保存至该同一存储桶中。
报错信息
报错类型:TypeError: 无法读取null的属性(读取'length')
问题分析与解决方案
核心原因
该报错通常是因为zip-bucket库在读取指定源路径时,未找到任何文件或源路径不存在,导致返回null值,后续代码尝试读取null的length属性触发错误。
解决步骤
- 验证源路径与文件存在性:确认
folder_name/路径下存在实际文件。GCS的“文件夹”是虚拟概念,只有当路径下有文件时才会被识别,空文件夹不会实际存在。 - 检查路径格式:尝试调整
fromPath的格式,比如去掉末尾斜杠folder_name测试,部分库对路径的斜杠处理存在差异。 - 权限验证:确保Cloud Run使用的服务账号拥有足够权限:至少需要
storage.objects.list(读取文件列表)和storage.objects.create(写入压缩包)权限。 - 提前校验文件数量:在压缩前手动列出路径下的文件,确认存在可压缩的文件:
const [files] = await bucket.getFiles({ prefix: 'folder_name/' }); console.log('可压缩文件数量:', files.length);
如果输出为0,说明源路径无文件,需先确认文件存储路径是否正确。
内容的提问来源于stack exchange,提问作者Ibraheem Azeem
相关产品推荐
相关产品推荐

