Skip to content

Unable to use NodeJS worker_threads module #18540

Closed

Description

@d0peCode

Issue Details

  • Electron Version:
    v5.0.2
  • Operating System:
    Windows 10

Expected Behavior

On app ready start nodejs worker which consoles string.

Actual Behavior

App crash immediately after run

To Reproduce

Additional Information

I used electron-forge to quick build app.

Activity

  1. walmat commented on Jun 25, 2019

    @walmat

    Having the same issue with Electron 4.x.x and Node 12.4. Same behavior and setup. Have you found a fix for this?

    I've tried:

    1. export NODE_OPTIONS=--experimental-worker in both the runtime script && in my ~/.bash_profile
    2. Running electron as a node process via the RUN_ELECTRON_AS_NODE=1 flag

    I've switched to using a global.window.Worker (web worker) for now, but would love to implement this lib in my project as soon as possible. If anyone can shed some light on this, or share a working example, that'd be great!

    edit: @sofianguy maybe you can lead us in the right direction, or give us a yes/no as to whether this is working in v4 or 5

  2. d0peCode commented on Jun 25, 2019

    @d0peCode
    Author

    Having the same issue with Electron 4.x.x and Node 12.4. Same behavior and setup.

    AFAIK Electron ship its own node fork, so your local 12.4 doesn't really matter.

    Have you found a fix for this?

    No, still waiting for response. There is pinned discussion #18397 which might be relevant somehow.

  3. infFenrir commented on Jul 11, 2019

    @infFenrir

    Having the same issue with Electron 5.0.6 and Windows 10 :(
    App crash...

  4. d0peCode commented on Jul 16, 2019

    @d0peCode
    Author

    Still no updates I still can not use threads in my electron app :(

  5. infFenrir commented on Jul 16, 2019

    @infFenrir

    I tested it on - Electron 4, 5, 6 and even 7 ....
    The result is the same, app crash :(

  6. i7soft commented on Jul 27, 2019

    @i7soft

    i have this problem too

  7. d0peCode commented on Aug 3, 2019

    @d0peCode
    Author

    Is there any chance of some statement from electron team? It's been months now (half year #17030)

  8. SaltFish001 commented on Aug 11, 2019

    @SaltFish001

    04(35B$JGE3MHE)_(S5M$G9
    Add NODE_OPTIONS(--experimental-worker) in your system environment variable.Restart terminal.

  9. walmat commented on Aug 11, 2019

    @walmat

    @SaltFish001 And what happens when you try to spawn a worker?

  10. SaltFish001 commented on Aug 11, 2019

    @SaltFish001

    @SaltFish001 And what happens when you try to spawn a worker?

    It's work.

  11. SaltFish001 commented on Aug 11, 2019

    @SaltFish001

    @SaltFish001 And what happens when you try to spawn a worker?

    sorry, it's seems no working.The process ended and no error was reported

  12. d0peCode commented on Aug 15, 2019

    @d0peCode
    Author

    I've tried it before even posting this issue. It doesn't change anything. Experimental flag for worker module was only required in node v11 if I remember correctly.

  13. 41 remaining items

  14. removed their assignment
    on Jul 29, 2020
  15. User0111 commented on May 22, 2021

    @User0111

    I tried asar: false, and it just works. Seems the problem is that script in worker_threads can't require modules in asar.

    @dsteinman tiddlywiki is a package in the node_modules, it is a self-contained 3rd party module, can only be required by name.

    My Solution:

    I'm using tiddlywiki, lodash and chokidar in my scripts, so:

    electron-builder

        asarUnpack: [
          '**/node_modules/tiddlywiki/**/*',
          '**/node_modules/lodash/**/*',
          '**/node_modules/chokidar/**/*',
          // dep of git.js
          '**/node_modules/fs-extra/**/*',
          '**/node_modules/dugite/**/*',
          // dep of fs-extra
          '**/node_modules/jsonfile/**/*',
          '**/node_modules/universalify/**/*',
          '**/node_modules/graceful-fs/**/*',
          '**/node_modules/at-least-node/**/*',
          // dep of dugite
          '**/node_modules/rimraf/**/*',
          '**/node_modules/progress/**/*',
          '**/node_modules/mkdirp/**/*',
          '**/node_modules/minimist/**/*',
          '**/node_modules/glob/**/*',
          '**/node_modules/checksum/**/*',
          '**/node_modules/got/**/*',
          '**/node_modules/tar/**/*',
          '**/node_modules/fs.realpath/**/*',
          '**/node_modules/inflight/**/*',
          '**/node_modules/path-is-absolute/**/*',
          '**/node_modules/optimist/**/*',
          '**/node_modules/minimatch/**/*',
          '**/node_modules/inherits/**/*',
          '**/node_modules/@sindresorhus/is/**/*',
          '**/node_modules/@szmarczak/http-timer/**/*',
          '**/node_modules/decompress-response@/**/*',
          '**/node_modules/duplexer3/**/*',
          '**/node_modules/cacheable-request/**/*',
          '**/node_modules/get-stream/**/*',
          '**/node_modules/lowercase-keys/**/*',
          '**/node_modules/mimic-response/**/*',
          '**/node_modules/p-cancelable/**/*',
          '**/node_modules/to-readable-stream/**/*',
          '**/node_modules/url-parse-lax/**/*',
          '**/node_modules/fs-minipass/**/*',
          '**/node_modules/chownr/**/*',
          '**/node_modules/safe-buffer/**/*',
          '**/node_modules/once/**/*',
          '**/node_modules/minizlib/**/*',
          '**/node_modules/wrappy/**/*',
          '**/node_modules/wordwrap/**/*',
          '**/node_modules/defer-to-connect/**/*',
          '**/node_modules/minipass/**/*',
          '**/node_modules/clone-response/**/*',
          '**/node_modules/get-stream/**/*',
          '**/node_modules/http-cache-semantics/**/*',
          '**/node_modules/keyv/**/*',
          '**/node_modules/lowercase-keys/**/*',
          '**/node_modules/brace-expansion/**/*',
          '**/node_modules/responselike/**/*',
          '**/node_modules/pump/**/*',
          '**/node_modules/normalize-url/**/*',
          '**/node_modules/yallist/**/*',
          '**/node_modules/json-buffer/**/*',
          '**/node_modules/balanced-match/**/*',
          '**/node_modules/concat-map/**/*',
          '**/node_modules/prepend-http/**/*',
          '**/node_modules/end-of-stream/**/*',
          // dep of chokidar
          '**/node_modules/is-binary-path/**/*',
          '**/node_modules/normalize-path/**/*',
          '**/node_modules/glob-parent/**/*',
          '**/node_modules/braces/**/*',
          '**/node_modules/anymatch/**/*',
          '**/node_modules/is-glob/**/*',
          '**/node_modules/readdirp/**/*',
          '**/node_modules/fsevents/**/*',
          '**/node_modules/binary-extensions/**/*',
          '**/node_modules/picomatch/**/*',
          '**/node_modules/is-extglob/**/*',
          '**/node_modules/fill-range/**/*',
          '**/node_modules/to-regex-range/**/*',
          '**/node_modules/is-number/**/*',
        ],
        extraResources: [
          {
            from: 'public/libs/wiki/wiki-worker.js',
            to: 'app.asar.unpacked/wiki-worker.js',
          },
          {
            from: 'public/libs/wiki/watch-wiki-worker.js',
            to: 'app.asar.unpacked/watch-wiki-worker.js',
          },
          {
            from: 'public/libs/git.js',
            to: 'app.asar.unpacked/git.js',
          },
        ],
    

    wow, our watch-wiki-worker.js dependes on my local git.js and git.js depends on chokidar and dugite.

    seems chokidar and dugite depends on tons of things, and things depend on things... So I have to use npx npm-remote-ls --flatten chokidar -d false -o false and so on to get the flattened dependency tree...

    If you miss one of the dep of dep, you will get MODULE_NOT_FOUND error too.

    worker manager

    const WIKI_WORKER_PATH = isDev
      ? path.resolve(__dirname, './wiki-worker.js')
      : path.resolve(process.resourcesPath, 'app.asar.unpacked', 'wiki-worker.js');
    const WIKI_WATCHER_WORKER_PATH = isDev
      ? path.resolve(__dirname, './watch-wiki-worker.js')
      : path.resolve(process.resourcesPath, 'app.asar.unpacked', 'watch-wiki-worker.js');
    1. list all 3rd party package that is required in worker_threads script, in the asarUnpack
    2. use extraResources to copy worker_threads scripts and local files that are required in worker_threads script, to app.asar.unpacked

    This solution works for me as well

    I was not able to use worker_threads with the following configuration:
    image

    I've used Electron Workers described here. Tasks processing is x2 faster now. I had a lot of sex love with Electron before I made it works but it is doable. it was really hard to get the list of all the dependencies(50) I have to add to asarUnpack. It's weird that so powerfull feature not documented well and needs so a lot of tricks to do. I would be happy to get know that I can do something simpler to make it works in another way even after all this hell.

  16. linonetwo commented on May 23, 2021

    @linonetwo

    @User0111 Actually I move to electron-forge, and use threads-plugin, so webpack pack standalone js file for worker to run, and it works fine and no asar-unpack now.

    https://github.com/tiddly-gittly/TiddlyGit-Desktop/blob/afacc142f65b2afd951edd25ee4b731b6da3ad3f/webpack.plugins.js#L9-L41

    https://github.com/tiddly-gittly/TiddlyGit-Desktop/blob/afacc142f65b2afd951edd25ee4b731b6da3ad3f/src/services/wiki/index.ts#L86

    But it takes me a long time refactor my code to electron-forge + typescript.


    And maybe it is because I upgraded to [email protected] ?

  17. m4heshd commented on Jun 24, 2021

    @m4heshd

    Electron really need to add more support for worker_threads especially since it's a god given for GUI development. I still find it very weird why the worker is unable to use Electron's patched fs. The most of my time I've spent debugging my projects, is related to Electron + asar + worker threads. There's always a "gotcha" waiting around the corner when going into production. @linonetwo I see that you're going through the same exact hell as I am since I see you on every worker_threads related issue that I'm also having.

  18. linonetwo commented on Jun 24, 2021

    @linonetwo
  19. m4heshd commented on Jun 24, 2021

    @m4heshd

    I finally make it worked...

    That's great. Unfortunately I cannot afford the time for any major refactoring right now. I'm just using my workers and dependencies unpacked for the moment. But love to move to a solid solution in the near future.

  20. Coukaratcha commented on Nov 30, 2021

    @Coukaratcha

    @linonetwo Thank you for your help. I have used the asar.unpacked trick and it worked like a charm. However, I am very disappointed that worker_threads are not working properly out of the box when the app is packaged.
    I see that you found a better solution with electron-forge but still I think it should be great that electron improves worker_threads integration. I am not satisfied with @codebytere's reply as I think that the issue was misunderstood: the issue is not that worker_threads are not working in renderer process, but that it cannot be possible to load modules from worker when using worker_threads from the main process. I think unpacking modules, even if it is a clever idea and a good temporary workaround, is not a good solution as we lost the perks of packaging.
    Is there any better solution if we want to keep nsis build target?

  21. JaspreetChhabra commented on May 21, 2022

    @JaspreetChhabra

    @linonetwo Thanks for the help. The mentioned solution did work but my worker is also using 'electron-store' which internally uses 'electron' Module. 'electron' needs to be mentioned in the dev-dependecies and I am not able to unpack the modules mentioned in the dev-dependencies using "asarUnpack" in package.json. Any workaround for this ?
    I am getting below error

    `error Error: Cannot find module 'electron'
    Require stack:

    • /Volumes/app 1.0.4/app.app/Contents/Resources/app.asar.unpacked/node_modules/electron-store/index.js`
  22. linonetwo commented on May 21, 2022

    @linonetwo

    @JaspreetChhabra  I think code in worker don't have access to electron modules, because electron module only accessible from electron main thread (not any worker thread).

    A workaround may be passing signal to trigger things in main thread and return data back to the worker thread. You may use threads plugin to simplify this, it supports rxjs, so passing things here and there is not that terrible.

    I think unpacking modules, even if it is a clever idea and a good temporary workaround, is not a good solution as we lost the perks of packaging.

    @Coukaratcha I'm currently not unpacking everything, I only unpack as need. https://github.com/tiddly-gittly/TidGi-Desktop/blob/master/docs/Development.md#how-to-add-dependency-that-used-in-a-worker_thread

    https://github.com/tiddly-gittly/TidGi-Desktop/blob/7831fa44bd27c18e1c25e62d78383d88c2930528/scripts/afterPack.js#L35-L50

    It makes building complex a bit, but it works and not increasing too much bundle size.

    well... 74M after install, but when zipped, no much , I think... See https://github.com/tiddly-gittly/TidGi-Desktop/releases TidGi-darwin-x64-0.7.7.zip 119 MB

  23. Cmaxd commented on Apr 17, 2024

    @Cmaxd

    @linonetwo thanks for your solution. do you know if electron has made any progress on this matter? It has been two years

  24. linonetwo commented on Apr 17, 2024

    @linonetwo

    I don't think electron will do anything new on this, because worker_thread is working with simple npm dependency.

    It depends on the npm package, if it use fs and path to locate other file, you have to move them to resource/ folder in afterPack script. I'm always doing this.

    But I'm not sure now, because @giladgd say it is possible to locate .node dependency without manually move them? withcatai/node-llama-cpp#199 (comment)
    I'm currently only move .node files to resource/ folder in afterBuild.js, and other JS dependency are bundled by electron-forge and works correctly in worker_thread.

  25. Cmaxd commented on Apr 17, 2024

    @Cmaxd

    @linonetwo Thanks for reply. In my case, I have an SDK, the SDK calls a .dll based on ffi-napi, I configured SDK externals in webpack, and move the SDK to asar.unpacked folder, which runs well in main thread;
    But now I want to call this SDK in worker_threads, it report an error MODULE_NOT_FOUND, to solve this problem, I need to bundle the SDK and worker's JS code together? and move the .node file in SDK's dependencies(ffi-napi ... ) to asar.unpacked folder ?

  26. galetahub commented on Aug 23, 2024

    @galetahub

    The main reason is that utilityProcess doesn't know where to find node_modules.
    With option asar: true electron package all of them (except native modules see AutoUnpackNativesPlugin) to archive app.asar.
    But inside the electron process, we can use modules from this archive like normal modules:
    import { SomeClass } from "app.asar/node_modules/some_module"
    So the main idea is to tell utilityProcess where the archived node_modules are located (app.asar/node_modules).

    I have found the solution in the VSCode source code:
    https://github.com/microsoft/vscode/blob/16bb31f856d64fded303542a7e4a628dc92e63a2/src/bootstrap-node.js

    Two functions enableASARSupport and removeGlobalNodeModuleLookupPaths did the job.
    In our case the function enableASARSupport must inject path app.asar/node_modules before app.asar.unpacked/node_modules.
    So utilityProcess module lookup paths first of all will look at app.asar/node_modules and then as normal lookup.

    Save path where unpacked node_modules is located to modulesPath:

    // main.ts
    
    let childPath = path.join(__dirname, 'my.worker.js');
    let modulesPath = path.join('./node_modules');
    
    if (app.isPackaged) {
      childPath = path.join(process.resourcesPath, 'app.asar.unpacked/.vite/build/my.worker.js');
      modulesPath = path.join(process.resourcesPath, 'app.asar.unpacked/node_modules');
    }

    Pass variable modulesPath to our utilityProcess worker via envs:

    childProcess = utilityProcess.fork(
        childPath,
        [],
        {
          stdio: 'pipe',
          serviceName: 'Utility Process',
          env: {
            'NODE_MODULES_PATH': modulesPath,
            ...
          },
        }
      );

    Configure forge.config.js to include the worker module in the unpack:

    // forge.config.js
    module.exports = {
      packagerConfig: {
        asar: {
          unpack: "**/.vite/build/*.worker.*",
        },
      },
      ...
     }

    Use hook to lookup app.asar/node_modules:

    // my.worker.ts
    const path = require('path');
    const fs = require('fs');
    const Module = require('module');
    
    // increase number of stack frames(from 10, https://github.com/v8/v8/wiki/Stack-Trace-API)
    Error.stackTraceLimit = 100;
    
    const removeGlobalNodeModuleLookupPaths = function () {
      if (typeof process?.versions?.electron === 'string') {
        return; // Electron disables global search paths in https://github.com/electron/electron/blob/3186c2f0efa92d275dc3d57b5a14a60ed3846b0e/shell/common/node_bindings.cc#L653
      }
    
      // TODO@esm this might not work anymore (https://github.com/microsoft/vscode/issues/226042)
    
      const Module = require('module');
      // @ts-ignore
      const globalPaths = Module.globalPaths;
    
      // @ts-ignore
      const originalResolveLookupPaths = Module._resolveLookupPaths;
    
      // @ts-ignore
      Module._resolveLookupPaths = function (moduleName, parent) {
        const paths = originalResolveLookupPaths(moduleName, parent);
    
        if (Array.isArray(paths)) {
          let commonSuffixLength = 0;
          while (commonSuffixLength < paths.length && paths[paths.length - 1 - commonSuffixLength] === globalPaths[globalPaths.length - 1 - commonSuffixLength]) {
            commonSuffixLength++;
          }
          return paths.slice(0, paths.length - commonSuffixLength);
        }
    
        return paths;
      };
    };
    
    /**
     * Helper to enable ASAR support.
     */
    const enableASARSupport = function () {
      // ESM-comment-begin
      const NODE_MODULES_PATH = process.env.NODE_MODULES_PATH;
      const NODE_MODULES_ASAR_PATH = process.env.NODE_MODULES_PATH.replace('.unpacked', '');
    
      // @ts-ignore
      const originalResolveLookupPaths = Module._resolveLookupPaths;
    
      // @ts-ignore
      Module._resolveLookupPaths = function (request, parent) {
        const paths = originalResolveLookupPaths(request, parent);
    
        if (Array.isArray(paths)) {
          for (let i = 0, len = paths.length; i < len; i++) {
            if (paths[i] === NODE_MODULES_PATH) {
              paths.splice(i, 0, NODE_MODULES_ASAR_PATH);
              break;
            }
          }
        }
    
        return paths;
      };
      // ESM-comment-end
    };
    
    // Remove global paths from the node module lookup (node.js only)
    removeGlobalNodeModuleLookupPaths();
    
    // Enable ASAR in our forked processes
    enableASARSupport();
    
    // Your worker code here
    (() => {
      const SomeClass = require('@some/package');
    
      SomeClass.start_long_running_job();
    
    })().catch((error) => {
      console.log('ERROR', error);
      process.exit(1);
    });

    Be careful not to use require/import any packages from node_modules before the function enableASARSupport call, because Error MODULE_NOT_FOUND will raise.
    Vite/webpack build can move require to the top of the code, so double-check it.

    Hope, this will help somebody

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions