nine-to-five
v1.0.5
Published
Imitate WebWorkers in Node
Downloads
3
Readme
Nine to Five
A partial implementation of the WebWorker API for Node.js.
Q: Why? We already have the worker_threads module built in to Node.js!
A: Yes, but it doesn't have the WebWorker API, nor all the Functions in WebWorkers' global scope. To reuse code the API must be the same.
This library is essentially a thin layer on top of worker_threads
to make it
look and behave like WebWorkers. See also
What's been added, below.
Status
Working, with unit tests, but see What's not supported.
For documentation, read the example and bullet points below, and optionally the comments in the source (here and here).
Example
File example-worker.js:
onmessage = ( message, transfer ) => {
const { a, b } = message.data // get inputs
postMessage( a + b ) // send back output
}
File example-script.js:
let { Worker } = require( 'nine-to-five' )
const w = new Worker( 'example-worker.js' )
w.postMessage( { a : 5, b : 6 } )
w.on( 'message', ( message, transfer ) => {
console.log( message.data ) // prints 11
w.terminate() // so the whole script will stop
} )
Output:
11
Installation
npm install nine-to-five
Contributing
Clone this repo. You can run tests with npm test
.
What's been added?
That is, how is this better than Node's built-in worker_threads module? (The example above could have been done using that alone, I think.)
- Workers can use importScripts().
- Workers can use the XMLHttpRequest API.
- Workers can access
on
,off
,onmessage
,addEventListener
,removeEventListener
,emit
, and postMessage. - Message events behave like they would in the browser, in this sense:
myWorker.postMessage(x)
sends the Worker a message{ data : x }
postMessage(x)
in the Worker sends out a message{ data : x }
- Workers can use close() to terminate themselves.
- Workers can use the atob() and btoa() functions.
What's not supported?
Some errors
- If the Worker script has a syntax error, the web implementation throws a
SyntaxError
, but we do not. - Similarly, we do not generate
messageerror
events.
Some Worker constructor options
Worker(script)
requiresscript
to be a filename relative to the current working directory; in particular, it cannot be a URL.Worker(script,options)
does not support theoptions.type
field, which means it assumes type"classic"
and never type"module"
.Worker(script,options)
does not support theoptions.credentials
field; it ignores it.
Some Worker APIs
- IndexedDB
- Performance and related classes
- WebSockets
- WorkerLocation
- WorkerNavigator
- You cannot create your own events, as with the
CustomEvent
class in the browser, because Node.js does not support constructing event objects. - The dump() function is not supported in Workers; it is non-standard.