Simplifies forking of worker processes and distributing tasks between them.
Simplifies spawning pool of worker processes and distributing tasks between them.
npm install worker-forker
In master process:
Forker = require'worker-forker'Forker;// Create forker. Specify worker file.var forker = __dirname + "/worker.js";// Spawn some worker processes.forkerspawnrequire'os'cpuslength;// Add some tasksforkeraddTask"task parameters"console.log"Got task result:" err result1 result2;;// Handle various errorsforkeron'error'console.log"Got error:" err;;// Wait until all tasks finishedforkerfinishconsole.log"All tasks finished!";;
In worker file (worker.js in this example):
var Worker = require'../index.js'Worker;// Init worker with function which executes tasks.var worker =setTimeoutconsole.log"Worker got task:" task parameters;callbacknull "result 1" "result 2";1000;;// Start processing tasks.workerstart;
NB! Task parameters and results are transformed to strings due to interprocess communication limitations. If you want to pass objects either way, you should handle conversion to/from strings yourself.