部署NestJS开发的Web Scraper至Cyclic.sh遇Chrome缺失问题
解决NestJS Web Scraper在Cyclic.sh部署后找不到Chrome的问题
核心问题原因
Cyclic.sh的构建(build)与运行环境是分离的,你在build阶段执行的npx puppeteer browsers install chrome只会在构建环境中安装Chrome,构建完成后该环境的缓存目录(/home/sbx_user1051/.cache/puppeteer)不会被同步到运行环境,导致运行时找不到Chrome。
解决方案
1. 将Chrome安装命令移至运行前执行
修改package.json的脚本,使用prestart和prestart:prod钩子(NPM会自动在对应start命令前执行带pre前缀的脚本),确保运行环境中先安装Chrome再启动服务:
"scripts": { "build": "nest build", "prestart": "npx puppeteer browsers install chrome", "start": "node dist/main", "prestart:prod": "npx puppeteer browsers install chrome", "start:prod": "node dist/main", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", "test:watch": "jest --watch", "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./test/jest-e2e.json" }
2. 配置Puppeteer缓存路径到项目目录
为了避免依赖环境默认缓存路径的权限或同步问题,设置环境变量PUPPETEER_CACHE_DIR指向项目内的目录:
- 在Cycl.sh控制台的项目环境变量中添加:
PUPPETEER_CACHE_DIR=.puppeteer_cache - 在项目根目录的
.gitignore文件中添加.puppeteer_cache/,避免提交缓存文件
3. 代码中明确指定Chrome路径
在启动Puppeteer时,通过executablePath明确指定安装后的Chrome路径,确保程序能找到它:
import puppeteer from 'puppeteer'; async function scrape() { const browser = await puppeteer.launch({ executablePath: puppeteer.executablePath(), // 其他必要配置(如headless模式等) }); // 爬虫逻辑 }
验证方法
重新部署后,查看Cyclic.sh的运行日志,确认prestart阶段成功执行了Chrome安装命令,且服务启动后能正常初始化Puppeteer实例。
内容的提问来源于stack exchange,提问作者TheOne
相关产品推荐
相关产品推荐

