AWS Lambda Node.js 使用pdf-creator-node生成PDF出现PhantomJS路径错误
问题根因
- 你传入的
phantomPath是相对路径,在AWS Lambda的执行环境中,代码部署后根目录为/var/task,相对路径解析失败后,底层依赖的html-pdf包会 fallback 到默认路径/usr/local/bin/phantomjs,这就是报错提示找不到该路径二进制文件的核心原因。 - 额外存在代码语法错误、写入路径无权限、二进制文件兼容性/权限不足的潜在问题。
修复步骤
- 替换为绝对路径的phantomPath
修改options配置中的phantomPath为Lambda环境下的绝对路径:
const options = { format: 'A3', orientation: 'portrait', height: '900px', width: '1100px', // 替换为Lambda下的绝对路径 phantomPath: '/var/task/node_modules/phantomjs-prebuilt/bin/phantomjs', };
- 修正代码语法错误
你当前的函数未声明async,但内部使用了await,会触发语法报错,同时document.data中的变量未定义,且Lambda仅/tmp目录可写,修改对应逻辑:
// 加async关键字,新增模板数据入参 export const generatePdf = async (template: string, filename: string, templateData: any) => { const templateFile = `src/templates/${template}.html`; try { // Read HTML Template const html = fs.readFileSync(templateFile, 'utf8'); const options = { format: 'A3', orientation: 'portrait', height: '900px', width: '1100px', phantomPath: '/var/task/node_modules/phantomjs-prebuilt/bin/phantomjs', }; const document = { html, // 替换为实际传入的模板数据 data: templateData, // 写入Lambda可写的/tmp目录 path: `/tmp/${filename}`, type: '', }; await pdf.create(document, options); return true; } catch (error) { console.log(error); throw Error(error); } }
- 确保phantomjs二进制兼容与可执行权限
- 不要在Windows/macOS环境下打包部署包,否则安装的phantomjs是对应本地系统的二进制,无法在Lambda的Linux环境运行,建议在Linux/WSL环境下执行依赖安装,或者指定平台安装依赖:
npm_config_platform=linux npm install phantomjs-prebuilt - 打包前确保
node_modules/phantomjs-prebuilt/bin/phantomjs有可执行权限,可执行chmod +x node_modules/phantomjs-prebuilt/bin/phantomjs添加权限后再打包。
- 可选兜底方案
如果上述配置仍不生效,可以在函数入口处手动指定phantomjs路径的环境变量:
process.env.PHANTOMJS_PATH = '/var/task/node_modules/phantomjs-prebuilt/bin/phantomjs'
内容的提问来源于stack exchange,提问作者axelfy
相关产品推荐
相关产品推荐

