node-inline-worker

Seamless workers for Node.js

Usage no npm install needed!

<script type="module">
  import nodeInlineWorker from 'https://cdn.skypack.dev/node-inline-worker';
</script>

README

👷‍♀️ node-inline-worker npm

Moves a node module into a Node.js Worker, automatically reflecting exported functions as asynchronous proxies.

You might already be familiar with the Workerize npm package, which is the web counterpart for this module. The feature list and API are the same:

  • Bundles a tiny, purpose-built RPC implementation into your node app
  • If exported module methods are already async, signature is unchanged
  • Supports synchronous and asynchronous worker functions
  • Works beautifully with async/await

Available for Node >=12 without runtime flags. Uses node's Worker Threads.

Install

npm install --save node-inline-worker

Usage

Pass a function to be executed in the Worker thread

const add = workerize(async (a, b) => {
  await new Promise(resolve => setTimeout(resolve, 1000))
  return a + b
})

async function main () {
  // Pre-curried use
  console.log('3 + 9 = ', await add(3, 9)) // Logs after 1 second
  console.log('1 + 2 = ', await add(1, 2)) // Logs after 1 second

  // Direct invocation
  const sequence = await workerize(function fib (n) {
    return n <= 1 ? n : fib(n - 1) + fib(n - 2)
  })(10)

  console.log(sequence) // logs `55`
}

main()

License

MIT License © Christophe Marois