Node.js+Puppeteer在Ubuntu部署失败,Windows本地正常的问题排查
Puppeteer部署Ubuntu 18服务器的问题原因分析
问题背景
原项目使用已废弃的html-pdf库生成PDF,改用Puppeteer后在Windows 11本地运行正常,但在Ubuntu 18服务器执行npm install时遇到两个连续问题:
- 首次执行出现
ENOMEM内存不足错误 - 释放并增加服务器内存后,又抛出
Error: Cannot find module 'puppeteer-core/internal/puppeteer-core.js'错误
环境信息
Node Version = 16.20.0 "puppeteer": "^20.9.0" "typescript": "^5.0.4"
PDF生成代码
import puppeteer from 'puppeteer'; export class PdfUtil { constructor() { } public writePdf(filePath: any, htmlData: any) { return new Promise(async (resolve, reject) => { try { const browser = await puppeteer.launch({ headless: 'new' }); const page = await browser.newPage(); await page.setContent(htmlData); await page.emulateMediaType('screen'); const pdfOptions = { printBackground: true, path: filePath, // The path where the PDF will be saved margin: { top: '1cm', right: '1cm', bottom: '1cm', left: '1cm' }, // Optional page margins }; await page.pdf(pdfOptions); await browser.close(); resolve(true); } catch (error) { reject(error); } }); } }
问题原因拆解
1. ENOMEM内存不足错误
Puppeteer安装过程中会自动下载对应版本的Chromium浏览器,这个下载及解压操作需要占用较多内存资源。Ubuntu 18服务器的可用内存不足以支撑该流程,导致npm进程因内存耗尽终止,抛出ENOMEM错误。
2. 模块找不到错误
这个错误的核心是版本兼容性不匹配:
- Puppeteer 20.x版本对系统环境要求较高,而Ubuntu 18的系统库(如glibc)版本偏旧,无法满足Chromium的运行依赖,导致安装过程中Chromium下载不完整或依赖缺失,进而引发内部模块路径异常。
- 同时,TypeScript 5.0.4与Node.js 16.20.0的组合存在兼容性边界,TypeScript 5.x对Node.js版本的推荐要求更高,可能在模块解析或编译阶段出现异常,间接触发模块找不到的错误。
内容的提问来源于stack exchange,提问作者Ashutosh
相关产品推荐
相关产品推荐

