nyominkhat itwizard
nyominkhat itwizard

Reputation: 11

Setting up fake worker failed: \"Cannot find module '/var/task/node_modules/pdfjs-dist/legacy/build/pdf.worker.mjs"

I am facing the issue after deployed my express server on vercel. The project is just for fun. I am trying to convert pdf to images and upload to database, supabase.

import { pdfToPng } from "pdf-to-png-converter";

const convertPdfToImg = async (filePath: string, output: string) => {
  const pngPage = await pdfToPng(filePath, {
    viewportScale: 2.0,
    outputFileMask: "buffer",
    outputFolder: output,
  });
  return pngPage;
};

export default convertPdfToImg;

and this is how I use

      const pdfBuffer = req.file.buffer;

      const tempDir = path.join("/tmp", "temp");
      if (!fs.existsSync(tempDir)) {
        fs.mkdirSync(tempDir, { recursive: true });
      }

      const pdfFilePath = path.join(tempDir, `${req.file.originalname}.pdf`);
      fs.writeFileSync(pdfFilePath, pdfBuffer);

      const content = await convertPdfToImg(pdfFilePath, tempDir);

I worked locally but after deployed I got the error, it say

"Setting up fake worker failed: "Cannot find module '/var/task/node_modules/pdfjs-dist/legacy/build/pdf.worker.mjs' imported from /var/task/node_modules/pdfjs-dist/legacy/build/pdf.mjs"."

I already try to use a lot of packages some of packages need to install extra libraries globally like "imagemagick"

Upvotes: 1

Views: 210

Answers (1)

wadiov
wadiov

Reputation: 1

I found a solution that worked for me.

I copied the file pdf.worker.mjs from pdfjs-dist/legacy/build/pdf.worker.mjs and placed it in the root directory, alongside my main JavaScript file ( app.js or server.js, depending on what you're using).

Then, I added the following code to my main JavaScript file:

import { GlobalWorkerOptions } from "pdfjs-dist/legacy/build/pdf.mjs";

app.use(express.static(".")); // Serve static files from the root directory

GlobalWorkerOptions.workerSrc = new URL(
  "./pdf.worker.mjs",
  import.meta.url
).toString();

This ensures that the worker file is correctly loaded by pdfjs-dist.

Upvotes: 0

Related Questions