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

使用pdfjs-dist在Astro服务端提取PDF内容报错:Promise.withResolvers is not a function

解决Astro服务端使用pdfjs-dist提取PDF内容时的Promise.withResolvers错误

问题原因

Promise.withResolvers()是ES2024新增的API,当前你的Node.js版本或Astro运行时环境不支持该语法,而新版pdfjs-dist已依赖此API,因此触发报错。

解决方案

方法一:降级pdfjs-dist到兼容版本

安装不依赖Promise.withResolvers的旧版本(如3.x系列):

npm install pdfjs-dist@3.11.174

同时调整worker路径(3.x版本的worker文件命名不同):

pdfjsLib.GlobalWorkerOptions.workerSrc = "../../node_modules/pdfjs-dist/build/pdf.worker.min.js";

方法二:添加Promise.withResolvers polyfill

若不想降级,可在导入pdfjsLib前手动实现该API补全:

if (!Promise.withResolvers) {
  Promise.withResolvers = function () {
    let resolve, reject;
    const promise = new Promise((res, rej) => {
      resolve = res;
      reject = rej;
    });
    return { promise, resolve, reject };
  };
}

import * as pdfjsLib from "pdfjs-dist";
// 后续代码保持不变

额外优化

代码中访问私有属性pdf._pdfInfo.numPages存在兼容性风险,建议替换为官方公开属性:

const maxPages = pdf.numPages;

内容的提问来源于stack exchange,提问作者amir mohammad golestani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:02:05