Cloud Functions中Firebase Storage下载至临时目录返回空Buffer问题
问题解决:指定
destination后GCS download返回空Buffer的原因及方案 原因
调用bucket.file(filePath).download()时,若传入destination参数,GCS客户端库会直接将文件内容写入目标路径的本地文件,不会在返回值中提供文件Buffer——这是API的设计逻辑,目的是避免同时在内存和磁盘中存储重复数据,优化资源占用。
解决方案
如果你既需要将文件保存到临时路径,又要获取文件Buffer,有两种可行方案:
方案1:先下载Buffer,再写入临时文件
适合小文件,内存占用可控:
import { writeFile } from 'fs/promises'; import { Storage } from '@google-cloud/storage'; import path from 'path'; import os from 'os'; async function downloadFile(filePath: string): Promise<[Buffer, string]> { const storage = new Storage(); const bucket = storage.bucket('**********'); const fileName = path.basename(filePath); const tempFilePath = path.join(os.tmpdir(), fileName); // 下载文件到内存Buffer const [buffer] = await bucket.file(filePath).download(); // 将Buffer写入临时文件 await writeFile(tempFilePath, buffer); return [buffer, tempFilePath]; }
方案2:先下载到临时文件,再读取Buffer
适合大文件,避免内存过载:
import { readFile } from 'fs/promises'; import { Storage } from '@google-cloud/storage'; import path from 'path'; import os from 'os'; async function downloadFile(filePath: string): Promise<[Buffer, string]> { const storage = new Storage(); const bucket = storage.bucket('**********'); const fileName = path.basename(filePath); const tempFilePath = path.join(os.tmpdir(), fileName); // 下载文件到临时路径,此时无Buffer返回 await bucket.file(filePath).download({ destination: tempFilePath }); // 从临时文件读取Buffer const buffer = await readFile(tempFilePath); return [buffer, tempFilePath]; }
内容的提问来源于stack exchange,提问作者carloberd
相关产品推荐
相关产品推荐

