josdejong / workerpool

Offload tasks to a pool of workers on node.js and in the browser
Apache License 2.0
2.06k stars 147 forks source link

TypeError: Cannot read property 'bind' of undefined, when using webpack to build the project with workerpool dependency. #327

Closed mai1x9 closed 2 years ago

mai1x9 commented 2 years ago

The project is build using webpack to make single js file. However when using webpack, it throws the error,

node_modules\workerpool\src\worker.js:49
    worker.send = process.send.bind(process);
                               ^
TypeError: Cannot read property 'bind' of undefined
    at Object.<anonymous> (node_modules\workerpool\src\worker.js:49:32)
    at Module._compile (internal/modules/cjs/loader.js:1201:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1221:10)
    at Module.load (internal/modules/cjs/loader.js:1050:32)
    at Function.Module._load (internal/modules/cjs/loader.js:938:14)
    at Module.require (internal/modules/cjs/loader.js:1090:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at Object.worker (node_modules\workerpool\src\index.js:20:16)

Referring to #170, the issue is when building with webpack. Without building with webpack the code works absolutely fine. Considering the example,

const workerpool = require('workerpool');

// create a worker pool using an external worker script
const pool = workerpool.pool(__dirname + '/myWorker.js');

// run registered functions on the worker via exec
pool.exec('fibonacci', [10])
    .then(function (result) {
      console.log('Result: ' + result); // outputs 55
    })
    .catch(function (err) {
      console.error(err);
    })
    .then(function () {
      pool.terminate(); // terminate all workers when done
    });

It does make sense that, using webpack, it will try to convert all js file to one main.js file. When trying to run myWorker.js, Since the file is not in /dist folder after build, It may look like the error would be File not Found. However to my great surprise, the error was is

node_modules\workerpool\src\worker.js:49
    worker.send = process.send.bind(process);
                               ^
TypeError: Cannot read property 'bind' of undefined
...so on

Any explain regarding this behaviour, I wonder if it is unable to spawn child process.

One way to fix the issue is to exclude the myWorker.js from webpack building it, and moving the myWorker.js to /dist folder.

However I would like to know if we can include myWorker.js with webpack.

josdejong commented 2 years ago

Yes, that is a known difficulty. See #189. I'll close this issue as a duplicate, please continue the discussion there.