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

如何在Node.js中将Supabase Storage返回的Blob保存为本地文件

Node.js环境下将Supabase Storage返回的Blob保存为本地文件

直接使用Node.js内置的文件系统模块即可完成写入,完整实现流程如下:

完整实现代码

// 引入依赖
const { createClient } = require('@supabase/supabase-js')
const fs = require('fs/promises')
// 替换为你的Supabase项目配置
const supabase = createClient('你的项目公网URL', '你的项目anon公开密钥')

/**
 * 从Supabase Storage下载文件并保存到本地
 * @param {string} bucketName 存储桶名称
 * @param {string} remoteFilePath 存储桶内的文件路径
 * @param {string} localSavePath 本地保存的完整路径
 */
async function saveSupabaseFileToLocal(bucketName, remoteFilePath, localSavePath) {
  // 调用download接口获取Blob数据
  const { data: blob, error } = await supabase
    .storage
    .from(bucketName)
    .download(remoteFilePath)
  
  if (error) throw new Error(`下载失败: ${error.message}`)

  // 将Blob转换为Node.js可写入的Buffer格式
  const fileBuffer = Buffer.from(await blob.arrayBuffer())

  // 写入本地磁盘
  await fs.writeFile(localSavePath, fileBuffer)
}

// 调用示例
saveSupabaseFileToLocal('media', 'avatar/123.jpg', './local-avatar.jpg')
  .then(() => console.log('文件保存成功'))
  .catch(err => console.error('操作失败', err))

注意事项

  • 若需要同步写入文件可替换为fs.writeFileSync,非必要场景推荐使用异步API避免阻塞主线程
  • 保存文件前需确保本地路径的父级目录已存在,否则会触发写入失败,可提前通过fs.mkdir(xxx, { recursive: true })创建目录
  • 若需下载大于10M的大文件,建议改用流写入方式减少内存占用:先获取文件的临时签名URL,再通过网络请求库以流的形式写入本地

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:15:00