在Firebase Cloud Functions中运行Puppeteer遇到问题
解决Firebase Cloud Functions中Puppeteer的运行问题
一、解决完整版Puppeteer体积超限问题
完整版Puppeteer自带Chrome二进制文件,导致函数包体积超出Firebase限制,可通过以下方式规避:
- 使用Firebase分层部署:将Chrome二进制文件单独打包为函数层,与业务代码分离部署。
- 创建层目录,安装Puppeteer时添加
--no-install-browser参数避免自带Chrome; - 下载适配Cloud Functions环境的Chrome二进制文件放入层目录;
- 部署层并在函数中引用,这样Chrome体积不会占用函数包配额。
- 创建层目录,安装Puppeteer时添加
- 启用生产依赖裁剪:执行
npm prune --production移除开发依赖,进一步压缩函数包体积。
二、Puppeteer-core的兼容浏览器方案
针对chrome-aws-lambda不兼容新版Puppeteer-core的问题,可选择以下替代方案:
- 使用@sparticuz/chromium:这是chrome-aws-lambda的维护分支,适配最新版Puppeteer-core与Node.js 16+环境。示例代码:
const puppeteer = require('puppeteer-core'); const chromium = require('@sparticuz/chromium'); exports.scheduledFunction = functions .runWith({ memory: '1GB', timeoutSeconds: 120 }) .https.onRequest(async (req, res) => { const browser = await puppeteer.launch({ headless: chromium.headless, executablePath: await chromium.executablePath(), args: [...chromium.args, '--no-sandbox', '--disable-setuid-sandbox'], defaultViewport: chromium.defaultViewport, }); // 业务逻辑 await browser.close(); res.send('执行完成'); });
- 直接调用环境自带Chrome:Firebase Cloud Functions的Node.js 18+运行时默认预装Chrome,可指定路径
/usr/bin/google-chrome作为executablePath配合Puppeteer-core使用。
三、其他补充解决方案
- 延长函数超时时间:Puppeteer启动与页面加载耗时较长,可将超时设置为120秒(最大支持540秒),配置示例:
exports.scheduledFunction = functions .runWith({ memory: '1GB', timeoutSeconds: 120 })
- 切换到第二代运行时:第二代运行时支持最大1GB函数包体积,启动速度更快,兼容性更好。在
firebase.json中配置:
{ "functions": { "runtime": "nodejs18", "gen2": true } }
- 确认临时目录权限:Puppeteer默认使用
/tmp目录存储临时文件,Cloud Functions环境下该目录具备读写权限,无需额外配置。
内容的提问来源于stack exchange,提问作者Jens Nielsen
相关产品推荐
相关产品推荐

