使用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
相关产品推荐
相关产品推荐

