Express定时任务部署Ubuntu后Firebase Storage出现pipe函数错误
问题:Ubuntu服务器部署Express定时任务时Firebase Storage上传报错
我在Express服务器中实现了每10分钟执行的定时任务,通过Gmail API扫描指定Gmail账户收件箱内特定主题的邮件,满足条件时将邮件内容及附件存储至Firebase Storage与Firebase实时数据库。本地环境运行完全正常,但部署到Ubuntu服务器后出现如下报错,服务器持续崩溃,数据无法存储:
/home/ubuntu/project_name/node_modules/@firebase/storage/node_modules/node-fetch/lib/index.js:650 body.stream().pipe(dest); ^ TypeError: body.stream(...).pipe is not a function at writeToStream (/home/ubuntu/project_name/node_modules/@firebase/storage/node_modules/node-fetch/lib/index.js:650:17) at /home/ubuntu/project_name/node_modules/@firebase/storage/node_modules/node-fetch/lib/index.js:1627:3 at new Promise (<anonymous>) at fetch (/home/ubuntu/project_name/node_modules/@firebase/storage/node_modules/node-fetch/lib/index.js:1407:9) at FetchConnection.send (/home/ubuntu/project_name/node_modules/@firebase/storage/dist/index.node.cjs.js:558:16) at doTheRequest (/home/ubuntu/project_name/node_modules/@firebase/storage/dist/index.node.cjs.js:1032:18) at Timeout._onTimeout (/home/ubuntu/project_name/node_modules/@firebase/storage/dist/index.node.cjs.js:816:13) at listOnTimeout (node:internal/timers:569:17) at process.processTimers (node:internal/timers:512:7)
经排查,错误出现在Firebase Storage上传附件的代码段:
const storageRef = firebase.storage().ref(`attachments/${attachment.attachmentId}`); const snapshot = await storageRef.put(buffer, { contentType: attachment.mimeType }); const downloadUrl = await snapshot.ref.getDownloadURL();
解决方案
检查并升级Node.js版本
这个报错核心是Node.js版本与node-fetch的API兼容问题:本地可能用了较新的Node.js(支持流的pipe方法),但服务器上的版本偏旧。- 在服务器执行
node -v查看当前版本,确保升级到v16及以上的LTS版本(比如v18或v20)。 - 升级后删除旧依赖重新安装:
rm -rf node_modules package-lock.json && npm install
- 在服务器执行
强制指定兼容的node-fetch版本
如果暂时无法升级Node.js,可在package.json中手动添加兼容版本的node-fetch,强制覆盖依赖:"dependencies": { // 其他依赖... "node-fetch": "^2.6.7" }然后执行
npm install重新安装依赖,解决版本不匹配问题。修改上传代码的Buffer处理逻辑
直接传入Buffer在部分环境下可能出现流处理异常,可将Buffer转换为Readable流再上传:const { Readable } = require('stream'); const storageRef = firebase.storage().ref(`attachments/${attachment.attachmentId}`); // 将Buffer转为可读流 const fileStream = Readable.from(buffer); const snapshot = await storageRef.put(fileStream, { contentType: attachment.mimeType }); const downloadUrl = await snapshot.ref.getDownloadURL();更新Firebase依赖包
旧版本的Firebase Storage可能存在跨环境的流处理bug,执行以下命令更新到最新稳定版:npm update firebase @firebase/storage
内容的提问来源于stack exchange,提问作者Ankit Sharma
相关产品推荐
相关产品推荐

