Error: Unable to initialize mock worker: "The module './pdf.worker.js' could not be located using 'pdfjs-dist' in a Next.js and TypeScript environment."

I've been attempting to utilize the 'pdfjs-dist' package in order to extract text from a pdf file stored in my AWS S3 bucket. However, when I execute the code, I encounter the following error:

Error: Setting up fake worker failed: "Cannot find module './pdf.worker.js'

This error has left me puzzled, and I'm unsure about how to resolve it. The code snippet I have looks like this:

import { NextResponse } from "next/server";
import * as PDFJS from 'pdfjs-dist';
import { TextItem } from 'pdfjs-dist/types/src/display/api';

export async function POST(
) {

    let myFiledata = await fetch("url to my S3 bucket")

    if (myFiledata.ok) {
        let pdfDoc = await PDFJS.getDocument(await myFiledata.arrayBuffer()).promise
        const numPages = pdfDoc.numPages
        for (let i = 0; i < numPages; i++) {
            let page = await pdfDoc.getPage(i + 1)
            let textContent = await page.getTextContent()
            const text = textContent.items.map((item) => (item as TextItem).str).join('');

            console.log(text)

        }

        return new NextResponse("Success", { status: 200 });
    } else {
      
        return new NextResponse("Internal Error", { status: 500 });
    }
}

I am unsure of what steps to take to resolve this issue. Should I place a specific file somewhere within my project, or is it related solely to the code?

I attempted different methods of initializing the pdf.worker.js such as using variations like:

PDFJS.GlobalWorkerOptions.workerSrc

And assigning values to various URLs like:

pdfjs-dist/legacy/build/pdf.worker.entry.js;
pdfjs-dist/legacy/build/pdf.worker.entry.entry;
pdfjs-dist/legacy/build/pdf.worker
pdfjs-dist/build/pdf.worker.min.js

I even tried calling the pdfjs version with:

https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfVersion}/pdf.worker.js

However, each time it indicates that these URLs are not recognized, so I may be making incorrect calls or simply far from finding the actual solution.

Answer №1

To fix the issue, I successfully resolved by relocating the pdf.worker.js file from its original location within my node_modules/pdfjs-dist/build/pdf.worker.js directory to the public folder. After moving it, I then copied the file path and updated the code with the new path like so:

PDFJS.GlobalWorkerOptions.workerSrc = "new path to pdf.worker.js"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I incorporate my custom component into an Angular 12 modal using NGZorro?

I want to incorporate my own component into an nzmodal. I attempted the following: <nz-modal [(nzVisible)]="isVisible" nzTitle="Create relation" (nzOnCancel)="handleCancel()" (nzOnOk)="handleOk()"> & ...

Difficulty displaying SVGs in VueJS when using Typescript

I'm facing a strange issue that seems like it should be easy to solve. When using Vue with JavaScript as CDN, everything works perfectly (just like it does in Angular or any other framework). <img src="/assets/images/icons/myicoin.svg> However ...

Elimination of any null value fields upon form submission in Angular 2

Hey everyone, I'm currently working on a project that uses a Model driven form. When I submit the form, I am encountering an issue where I get null values in my formGroupObj.value. I need to find a way to remove fields with null values. Here is how t ...

Ways to retrieve a particular element within an array

I am looking to access each individual element of the "to" value within the children property of my array. const items = [{ name: 'Administrator', children: [ { name: 'Catalog', to: 'catalog' }, and he ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

Developing a custom typography attribute for themes in Material-UI with TypeScript

I have encountered an issue with my code where the palette works fine, but there seems to be a problem with the typography section without any errors being thrown: Here is a breakdown of the steps I took: Firstly, I imported the module import "@mui ...

Error Domain AWSS3PresignedURLErrorDomain in iOS with AWSSDK version 2

Recently, I have been utilizing AWSSDK V2 with iOS 8 and have gone through various sample code bases to set up Cognito with proper access to my S3Bucket. For reference, I followed this example: https://github.com/awslabs/aws-sdk-ios-samples/tree/master/S3 ...

"Using RxJS to create an observable that filters and splits a string using

I need to break down a string using commas as separators into an observable for an autocomplete feature. The string looks something like this: nom_commune = Ambarès,ambares,Ambares,ambarès My goal is to extract the first value from the string: Ambarès ...

How can I move the cursor to the beginning of a long string in Mat-autocomplete when it appears at the end?

I'm struggling to figure out how to execute a code snippet for my Angular app on Stack Overflow. Specifically, I am using mat-autocomplete. When I select a name that is 128 characters long, the cursor appears at the end of the selected string instead ...

"Step-by-step guide to using InfoType or other data types from the google-cloud/dlp library in a Node.js TypeScript environment

Currently utilizing Google cloud DLP in harmony with nodejs. Once the import of DLP from "@google-cloud/dlp" is complete, I am seeking guidance on how to efficiently import InfoType, Likelihood, IInspectContentRequest, and any other types required from t ...

Guide on generating a request through iteration using Javascript

I'm currently working on a request that involves multiple methods, and I want to streamline the code by using an enum to iterate through and construct the request. However, my attempt at doing this has resulted in unexpected outcomes. The original co ...

Incorporating SVG graphics within a SharePoint web part

I am in the process of developing a webpart for SharePoint using the SharePoint Framework, TypeScript, and ReactJS. I have encountered an issue while trying to incorporate an svg image into my webpart code, resulting in build errors. Initially, I used the ...

React useEffect Hook fails to trigger after redux State update

I recently created a React.FunctionComponent to serve as a wrapper for children and perform certain actions after some redux dispatch operations in Typescript, but I'm facing issues. Here is the code snippet of the wrapper: import React, {useState, us ...

Ways to manage multiple requests simultaneously on my API

I am encountering an issue with my API endpoint that manages available rooms in a hotel. Whenever a customer sends a POST/GET request to the API, it searches for an available room and assigns the room number to them. Here is the code snippet: const db = aw ...

The debugger extension for Visual Studio Code in Chrome, [webkit-debug-adapter], received a response from the target application, but was unable to find any valid target

I am currently working on an Angular/TypeScript application and have been able to debug the TypeScript code in Chrome thanks to the map files. Recently, I decided to install the Debugger for Chrome extension from Visual Studio Marketplace. You can find it ...

Discover properties of a TypeScript class with an existing object

I am currently working on a project where I need to extract all the properties of a class from an object that is created as an instance of this class. My goal is to create a versatile admin page that can be used for any entity that is associated with it. ...

Hoping that SWR library would provide cached data, but unfortunately that is not the case

I am currently utilizing the Vercel SWR hook usrSWR and I have an expectation that I will be able to access the cached data in a distant component without the need for using context or any other global state manager. In particular, I am storing cache data ...

Customize the date format of the Datepicker in Angular by implementing a personalized pipe

I am dealing with a datepicker that defaults to the MM/dd/yyyy format, and I need it to adjust based on the user's browser language. For example, if the browser language is English India, then the format should be set to dd/MM/yyyy as shown below. Be ...

Methods for verifying an empty array element in TypeScript

How can I determine if an element in an array is empty? Currently, it returns false, but I need to know if the element is blank. The array element may contain spaces. Code let TestNumber= 'DATA- - -' let arrStr =this.TestNumber.split(/[-]/) ...

Utilizing identical elements on a single page can lead to glitches within Next.js

Update: A codesandbox has been created to demonstrate the issue. There are 3 components that allow file uploads, but the first component always gets updated regardless of which one is chosen. Check out the codesandbox here The latest version of Next.js is ...