4

Question

I'm trying to use web workers in electron. So far I'm able to instanciate the worker process from the renderer process, but when I try to do a require('some_module') in the worker process the process crashes with the error.

Cannot find module 'some_module'.

The cjs loader cannot find my module apparently. But when I make the same require call from the renderer process, I'm able to require the module.

I've followed all the steps mentioned here. Also I've set the optionnodeIntegrationInWorker: true and I can make require calls to node inbuilt modules like fs with no problems.


A few observations

  1. __dirname in the rendered process resolves to

    root/node_modules/electron/dist/resources/electron.asar/renderer

    and in the worker process resolves to

    root/node_modules/electron/dist/resources/electron.asar/worker

    as far as I've done the reading the require function should be able to find my module in the node_modules dir which is parent to both the renderer and worker dir

  2. A quick look at the process global in the worker reveals that process.type is equals worker while process.argv[1] is equals --type=renderer which I find strange.


Meta: Electron version = "4.0.0", platform = "win32", arch = "x64", node version = "v10.11.0"

Any help in this regard would be appreciated.

Nishkal Kashyap
  • 960
  • 7
  • 17

2 Answers2

1

Ok. As a workaround, I use this.

    const paths = [
        path.join(process.resourcesPath, 'app.asar', 'node_modules'),
        path.join(process.resourcesPath, 'app', 'node_modules'),//when asar is disabled
        process.resourcesPath.replace(/electron[\\/]dist[\\/]resources/g, '')
    ];

    paths.map((path) => {
        global.require.main.paths.push(path);
    });

The above snippet manually adds the paths node looks to resolve the required module.

Nishkal Kashyap
  • 960
  • 7
  • 17
0

You don't need to do the above. Just do a require from app.asar's node_modules:

   const myModule = require(process.resourcesPath + '/app.asar/node_modules/' + 'modulename');

Thank me later ;