centralized

0.1.2 • Public • Published

centralized

build status Coverage Status

Social Media Photo by Alex wong on Unsplash

A module to delegate to the main thread tasks meant to run for all forked threads.

import cluster from 'node:cluster';
import {cpus} from 'node:os';

import centralized from 'centralized';

const appHelper = centralized({
  // properties can have any value
  connection: null,

  // methods can be used seamlessly from worker ot main
  query: async function(sql, ...values) {
    const stmt = this.connection.prepare(sql);
    return await stmt.exec(...values);
  },

  // the init method executes once only in the main thread ...
  init() {
    // ... and it can pollute its context with values
    this.connection = db.connect({user, pass, stuff});
  }
});

if (cluster.isWorker) {
  // this will return the result from the db
  const result = await appHelper.query(
    'SELECT * FROM table WHERE thing = ?',
    'cool'
  );
  console.log(result);
}
else {
  // perform the query all over the place
  for (let {length} = cpus(), i = 0; i < length; i++)
    cluster.fork();
}

And that's all folks 🥳

Readme

Keywords

none

Package Sidebar

Install

npm i centralized

Weekly Downloads

32

Version

0.1.2

License

ISC

Unpacked Size

7.79 kB

Total Files

7

Last publish

Collaborators

  • webreflection