var cluster = require('cluster'),
os = require('os');
if (cluster.isMaster) {
let files = ['1', '2', '3', '4', '5', '6', '7'];
let trySpawnNewWorker = function () {
if (files.length > 0) {
let params = {};
params.file = files.shift();
cluster.fork(params); //params becomes part of env
}
}
for (let i = 0; i < os.cpus().length; i++) {
trySpawnNewWorker();
}
// if one dies, spawn another to continue processing files
cluster.on('exit', () => trySpawnNewWorker());
} else {
let file = process.env['file'];
console.log('new worker, file=', file);
// emulating long file tasks
setTimeout(() => { console.log('done:', file); process.disconnect(); },
2000);
}