node-threads-pool

worker threads pool

Usage no npm install needed!

<script type="module">
  import nodeThreadsPool from 'https://cdn.skypack.dev/node-threads-pool';
</script>

README

node-threads-pool

David deps node version npm download npm license

Installation

npm install node-threads-pool

Usage

const tp = new Eve(filename, threadCount);
  • @param {String} filename: The path to the Worker’s main script or module. Detail description
  • @param {Number} threadCount: The number of threads in the thread pool
tp.run(workerData);
  • @param {Object} workerData: Any JavaScript value that will be cloned and made available as require('worker_threads').workerData. Detail description
  • @return {Promise} The result
const thread = new Thread(func);
  • @param {Function} func: some code

Example

1. Open 20 threads to perform some calculations

// main.js

const {Eve} = require('node-threads-pool');

const tp = new Eve('thread.js', 20);
module.exports = async (data) => {
  return await tp.run(data);
};

// thread.js

const {Thread} = require('node-threads-pool');

const thread = new Thread(async (data) => {
  return await doSomething(data);
});

Or write to the same JS file

// main.js

const {Eve, Thread, isMainThread} = require('node-threads-pool');


if(isMainThread) {
  const tp = new Eve(__filename, 20);
  module.exports = async function(data) {
    return await tp.run(data);
  };
} else {
  new Thread(async (data) => {
    return await doSomething(data);
  });
}

2. Render PUG to HTML

const pug = require('pug');
const os = require('os');
const {Eve, Thread, isMainThread} = require('node-threads-pool');

if(!isMainThread) {
  const options = {};
  new Thread(_data => {
    const {template, data} = _data;
    options.data = data;
    return pug.renderFile(template, options);
  });
} else {
  const tp = new Eve(__filename, os.cpus().length);
  module.exports = async (template, data) => {
    return await tp.run({
      template, data
    });
  };
}

Test

npm run eve