You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在AWS Lambda中使用自定义路径wkhtmltopdf遇TypeError: callback is not a function

问题描述

我正在开发一个使用wkhtmltopdf Node.js库生成PDF的AWS Lambda函数,已将自定义wkhtmltopdf二进制文件部署到Lambda层,并尝试通过executablePath选项指定其路径。

执行Lambda函数时出现以下错误:

TypeError: callback is not a function
    at handleError (/opt/nodejs/node_modules/wkhtmltopdf/index.js:170:7)
    at ChildProcess.<anonymous> (/opt/nodejs/node_modules/wkhtmltopdf/index.js:133:7)
    at ChildProcess.emit (node:events:519:28)
    at ChildProcess.emit (node:domain:488:12)
    at ChildProcess._handle.onexit (node:internal/child_process:294:12)

我的简化代码如下:

const WKHTMLTOPDF_PATH = '/opt/bin/wkhtmltopdf';

return new Promise((resolve, reject) => {
    try {
        const pdfStream = wkhtmltopdf(htmlBuffer, {
            pageSize: 'A4',
            marginTop: 30,
            marginRight: 20,
            marginBottom: 60,
            marginLeft: 20,
            printMediaType: true,
            enableLocalFileAccess: true,
            encoding: 'UTF-8',
            footerSpacing: 10,
            zoom: 1.0,
            dpi: 300,
            quiet: true,
        }, {
            executablePath: WKHTMLTOPDF_PATH, // Custom binary path
        });

        streamToBuffer(pdfStream)
            .then(buffer => resolve(buffer))
            .catch(err => reject(err));
    } catch (error) {
        reject(error);
    }
});

关键细节:

  • wkhtmltopdf二进制文件部署在Lambda层的/opt/bin/wkhtmltopdf路径下
  • htmlBuffer包含有效的HTML内容
  • streamToBuffer函数用于处理流并转换为Buffer
  • 已确认二进制文件存在于指定路径,但错误仍持续出现

解决方案

这个错误的核心原因是调用wkhtmltopdf的参数格式不正确。

根据wkhtmltopdf Node库的API规范,executablePath属于配置项的一部分,应该放在第二个参数的对象里,而非单独作为第三个参数传入。

修改后的代码如下:

const WKHTMLTOPDF_PATH = '/opt/bin/wkhtmltopdf';

return new Promise((resolve, reject) => {
    try {
        const pdfStream = wkhtmltopdf(htmlBuffer, {
            pageSize: 'A4',
            marginTop: 30,
            marginRight: 20,
            marginBottom: 60,
            marginLeft: 20,
            printMediaType: true,
            enableLocalFileAccess: true,
            encoding: 'UTF-8',
            footerSpacing: 10,
            zoom: 1.0,
            dpi: 300,
            quiet: true,
            executablePath: WKHTMLTOPDF_PATH // 将executablePath移到主配置对象中
        });

        streamToBuffer(pdfStream)
            .then(buffer => resolve(buffer))
            .catch(err => reject(err));
    } catch (error) {
        reject(error);
    }
});

补充说明

当传入第三个参数时,库会误将其识别为回调函数,但实际传入的是对象,因此触发了"callback is not a function"错误。将executablePath合并到第二个配置参数对象中即可解决问题。

另外,需确保Lambda层的二进制文件具备可执行权限(部署时执行chmod +x /opt/bin/wkhtmltopdf),虽然已确认文件存在,但权限问题可能导致后续执行异常。


内容的提问来源于stack exchange,提问作者Deepak Boniface Cardoza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:36:14