workerjs
Server Web Workers for node.js that work.
This is a modified version of the workerjs library that handles events specific to the child_process in node.js.
Installation
This module is installed via npm:
$ npm install workerjs-node
Background
Web Workers are part of the HTML 5 spec and:
defines an API that allows Web application authors to spawn background workers running scripts in parallel to their main page. This allows for thread-like operation with message-passing as the coordination mechanism
In effect, it allows you to get the benefit of multi-talking and multi-threading in single-threaded Javascript, as well as the safety of the event loop.
You can achieve this in node.js using the child_process.fork method, but then you have to use a different API.
This module normalizes the Web Worker API for server-side javascript in node.js with the hopes that we can build more multi-tasking modules built on the Web Worker standard that will work on both the server and the client-side using browserify.
Example Usage
By using Web Workers you can do CPU-intensive operations without blocking the event-loop and incoming IO:
// app.js - run with "node app.js"var worker = '/path/to/fibworker.js';worker {to;};worker;
// fibworker.js - CPU web worker codeself {self;};{return n > 1 ? + : 1;}
Node Mode - allowing require()
I've also added a "node-friendly" option that allows the Web Worker to use
require() and other node.js conventions. To use this, just pass a boolean
value of true
through to the second argument of the Worker
contructor:
// app.js - run with "node app.js"var worker = '/path/to/gammaworker.js' true;worker;worker;
// gammaworker.js - uses requirevar gamma = ;self {;};
Also, if you provide a module.exports
function it will be executed as
an entry point of the web worker. This emulates the browserify transform
behaviour in webworkify:
// app.js - run with "node app.js"var worker = '/path/to/gammaworker2.js' true;worker;worker;
// gammaworker2.js - uses requirevar gamma = ;module {;};