Skip to content

lurchmath/nine-to-five

Repository files navigation

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) requires script to be a filename relative to the current working directory; in particular, it cannot be a URL.
  • Worker(script,options) does not support the options.type field, which means it assumes type "classic" and never type "module".
  • Worker(script,options) does not support the options.credentials field; it ignores it.

Some Worker APIs

About

Imitate WebWorkers in Node

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published