#ReferenceError: Worker is not defined

22 messages · Page 1 of 1 (latest)

trim torrentBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

wanton pelican
bright crown
#

Why would it just magically know what that is

#

you need to import it.

wanton pelican
#

i tried importing like this

#

but i'm getting this cant resolve error

#

can you tell me from where i should import the worker?

bright crown
#

what node version.

wanton pelican
#

18

#

& i'm using next.js 13.4.9

#

do i have to install some package in order to get this working?

bright crown
#

it has nothing to do with nextjs

#

it has to do with your node

bright crown
wanton pelican
#

hmm i dont want to upgrade to 14 atm

#

im worried about breaking stuff

wanton pelican
wanton pelican
#

i installed node 20.9

#

the issue is still there

wanton pelican
#

i'm still facing this issue

#

after checking the type it created a worker, but, when I did worker.postMessage(), the message event listener doesn't listen to anything

worker-client.ts

 
import { EncoderWorkerRes } from '../types';
import { serializeAudioBuffer } from './audio-trimmer-helpers';

let worker: Worker;

if (typeof Worker !== 'undefined') {
  worker = new Worker('./worker.js');
  console.log('worker-client', worker);
} else {
  console.error('Web workers are not supported in this environment.');
}

/**
 * use worker to encode audio
 */
export default function encode(audioBuffer: AudioBuffer, type: string): Promise<Blob> {
  console.log('incode function called');

  const id = Math.random();

  return new Promise((resolve, reject) => {
    if (!worker) {
      return reject(new Error('Worker is not defined'));
    }

    const audioData = serializeAudioBuffer(audioBuffer);
    if (worker.postMessage) {
      console.log('post message is present');
      worker.postMessage({
        type,
        audioData,
        id,
      });
    }

    /**
     * Worker message event listener
     */
    const listener = ({ data }: MessageEvent<EncoderWorkerRes>) => {
      console.log('inside encode promise listener', { data });
      if (!data || data.id !== id) return;

      if (data.success) {
        resolve(data.data);
        console.log('inside encode promise resolve', { data });
      } else {
        console.log('inside encode promise reject', { data });
        reject(new Error(data.message));
      }

      worker.removeEventListener('message', listener);
    };

    worker.addEventListener('message', listener);
  });
}