@krakenjs/subprocess-robot
v2.2.0
Published
Create processes, process pools, and message between processes
Downloads
23
Readme
SubProcess Robot
Create subprocesses and deal with messaging. Good for delegating tasks to a differnet process
Import a function and run it using a child process
Before:
import { slowSynchronousTask } from "./synchronous-tasks";
export function synchronousTask(options) {
return slowSynchronousTask(options);
}
After:
import { spawnProcess } from "subprocess-robot";
export async function asynchronousTask(options) {
const { slowSynchronousTask } = await spawnProcess.import(
require.resolve("./synchronous-tasks")
);
return await slowSynchronousTask(options);
}
Load balance your task between a pool of processes
Before:
import { slowSynchronousTask } from "./synchronous-tasks";
export function synchronousTask(options) {
return slowSynchronousTask(options);
}
After:
import { spawnProcessPool } from "subprocess-robot";
export async function asynchronousTask(options) {
const { slowSynchronousTask } = await spawnProcessPool.import(
require.resolve("./synchronous-tasks")
);
return await slowSynchronousTask(options);
}
Manually create a subprocess and send messages between
Parent process:
import { spawnProcess } from 'subprocess-robot';
const childProcess = spawnProcess({
script: require.resolve('./child')
});
childProcess.on('getUser', ({ id ) => {
return {
id,
name: 'Daniel',
logout() {
// log the user out
}
}
});
Child process:
import { attachProcess } from "subprocess-robot";
const parentProcess = attachProcess();
let user = await parentProcess.send("getUser", { id: 1337 });
console.log(`Logging ${user.name} out`);
await user.logout();
Create a pool of processes and delegate tasks
Parent process:
import { spawnProcessPool } from "subprocess-robot";
const childProcessPool = spawnProcessPool({
script: require.resolve("./child"),
});
let result = childProcessPool.send("do_some_blocking_task", data);
Child process:
import { attachProcess } from "subprocess-robot";
const parentProcess = attachProcess();
parentProcess.on("do_some_blocking_task", (data) => {
return slowSynchronousCompile(data);
});
Manually create a pool of processes and import a function
Parent process:
import { spawnProcessPool } from "subprocess-robot";
const childProcessPool = spawnProcessPool();
let { doSomeBlockingTask } = await childProcessPool.import(
require.resolve("./blockingTask")
);
let result = await doSomeBlockingTask(config);
Child process:
export function doSomeBlockingTask(config) {
return slowSynchronousCompile(config);
}
Quick Start
npm install --save subprocess-robot
Tests
Run the tests:
npm test