Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including mgr with all npm packages installed. Try it out:

var mgr = require("mgr")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

mgr v1.0.1

*For easily managing slave processes.*

mgr

Easier multithreading for Node.

Travis branch npm npm

Why?

Because multi-threaded node applications are unwieldy to work with, and I needed to work with them.

API

.job

Used by new child processes to expose functions (tasks) to parent processes.

It takes two arguments:

  • The name of the job (case sensitive).
  • A function to call when it's ready.
import { job } from 'mgr'

job('compute PI', () => {
    // do stuff
})

Jobs will only run when called by their parent process, and must always return a promise. If you've got a sweet Babel setup, I recommend using async functions. They're way nicer and crafted from unicorn tears.

job('do things', async (name) => {
    // things
    return 10 // Automagically promisified.
})

When a job finishes, the value is sent to the parent process (same goes for errors).

.Fork

Fork creates a new child node process and aims it at a file path you pass it. Any jobs declared by the child process can be run through Fork.

Paths must be absolute.

// Import the Fork class.
import { Fork } from 'mgr'

// The absolute path to a .js file.
const file = `${__dirname}/slave-code.js`

// Spawns a new process.
const slave = new Fork(file)

fork.run

Starts a job in the child process, returning a promise.

Job names are case-sensitive.

slave.run('compute PI')
    .then(console.log)
    .catch((error) => console.log('Oh noes!'))

If the job is expecting arguments, you can pass one immediately after the job name.

slave.run('encrypt', {
  data: 'Nuclear launch codes: ...',
  phrase: 'potatoes are lovely',
}).then((result) => console.log(result))

To keep stuff simple, only one argument is allowed.

Installing

From npm

$ npm install mgr --save

From GitHub

$ git clone https://github.com/PsychoLlama/mgr.git
$ cd mgr
$ npm install
$ npm run build

Running tests

First, install from GitHub. npm only has the compiled code.

Be sure to run the build first:

# Run once.
$ npm run build

# OPTIONAL: watch for changes.
$ npm run build -- --watch

Now you can run the tests.

$ npm test

mgr
Abbreviation, "manager"
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free