Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Nodejs Module into A Web Worker

I'm intending to use web worker inside my Node.js application for some concurrent tasks. However since the 'webworker-threads' module follows the implementation of HTML5 web worker, requiring Nodejs modules like require("fs") inside web worker does not work. importScripts() can load js files but I would like a functionality inside the web worker so that I can require npm-installed modules. Is there a workaround for that?

like image 432
JJin Avatar asked Jan 01 '13 02:01

JJin


People also ask

Can I use node modules in browser?

Thanks to some creative engineers, it is now feasible to use Node. js modules in browsers, but not directly. Being able to call Node. js modules from JavaScript running in the browser has many advantages because it allows you to use Node.

What is the difference between service worker and web worker?

Unlike web workers, service workers allow you to intercept network requests (via the fetch event) and to listen for Push API events in the background (via the push event). A page can spawn multiple web workers, but a single service worker controls all the active tabs under the scope it was registered with.

What is web worker node js?

Node. js worker threads have proven to be the greatest solution for CPU performance because of the following features: It runs a single process with multiple threads. Runs single JS Engine instance per thread. Executes one event loop per thread.


1 Answers

author of webworker-threads here. Thank you for using the module!

There is a default native_fs_ object with the readFileSync you can use to read files.

Beyond that, I've mostly relied on onejs to compile all required modules in package.json into a single JS file for importScripts to use, just like one would do when deploying to a client-side web worker environment. (There are also many alternatives to onejs -- browserify, etc.)

Hope this helps!

like image 97
audreyt Avatar answered Sep 17 '22 06:09

audreyt