6

How do we add worker thread in Electron JS? I have tried below which works fine in dev mode.

const worker = new Worker(path.join(__dirname, 'worker.js'));

But this causes error when the app is packaged, it is looking for worker.js inside app.asar. Even with the worker.js included in build/files.

Ram Kumar
  • 828
  • 2
  • 10
  • 27
  • 8 months ago, did you found a way to that? – LeonanCarvalho Mar 12 '21 at 20:38
  • No, I ended up using multiple renderer process as workers. – Ram Kumar Mar 14 '21 at 07:27
  • my solution was to unpack the workers but I can't require my modules, only node native modules. I also tried the cluster module, but it forks the entire electron process and causes bugs. May you can share your technic ? – LeonanCarvalho Mar 16 '21 at 12:41
  • I required only 2 workers, so I just created 2 more renderer process without any UI, it was also easier to interact with the renderer process since we could use electron's IPC modules. – Ram Kumar Mar 17 '21 at 13:40
  • I know this has been posted more than two years ago, but how did you communicate between the two render processes? I am currently facing your exact issue at the moment. – Barbarian772 Apr 19 '23 at 06:48
  • Hey, I actually have the same problem. Is there any solution available? – Wokers Apr 20 '23 at 14:15
  • @Wokers I've added an answer I think may help you. – Slbox Apr 20 '23 at 20:52

2 Answers2

1

I actually have found the answer on Webpack documentation.

new Worker(new URL('./worker.js', import.meta.url));

and it worked for me. https://webpack.js.org/guides/web-workers/

Wokers
  • 107
  • 3
  • 13
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 28 '23 at 03:20
0

You probably need to do a patch like this instead of using __dirname, because __dirname will resolve to the ASAR when in production, as you have found:

const { app } = require('electron');

const rootPath = app.isPackaged ? app.getAppPath() : __dirname;
const worker = new Worker(path.join(rootPath, 'worker.js'));

https://www.electronjs.org/docs/latest/api/app#appispackaged-readonly

Note that based on your exact setup you may need to navigate up or down a folder in your production app, in which case you can use something like:

const rootPath = app.isPackaged ? app.getAppPath() : path.join(__dirname, '..');
Slbox
  • 10,957
  • 15
  • 54
  • 106