1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import { Worker, isMainThread, parentPort, workerData } from 'worker_threads'; import fs from 'fs'; import { execSync } from 'child_process';
let PATH = './packages';
const clusterDo = () => { try { execSync('pnpm lint --fix', { cwd: workerData.path, }); parentPort.postMessage(workerData.path + ': success'); } catch (e) { parentPort.postMessage(workerData.path + ': failed'); } };
const handleMessage = (fn, errors) => (path) => { const name = path?.split(':'); if (name?.[1]?.includes('failed')) { errors.push(name?.[0]); } fn(); };
const doNext = (countOne, cutOne, errors, getIdx, names, getNum, type) => { const idx = getIdx(); const num = getNum(); console.log('num: ', num, idx, type); if (idx >= names.length) { if (num === 0) { console.log('errors: ', errors); } return; } const worker = new Worker('./do.mjs', { workerData: { path: `${PATH}/${names[idx]}`, } });
countOne(type);
worker.on( 'message', handleMessage(() => doNext(countOne, cutOne, errors, getIdx, names, getNum), errors) ); worker.on('error', doNext); }
const mainDo = () => { let MAX_THREAD = 15; const names = fs.readdirSync(PATH); console.log('Main thread starting...', names);
let idx = 0; let num = 0; const errors = [];
const countOne = type => { idx++; if (type === 'new') { num++; } }
const cutOne = () => { num--; }
const getNum = () => num;
const getIdx = () => idx;
while (idx < MAX_THREAD) { doNext(countOne, cutOne, errors, getIdx, names, getNum, 'new'); } }
function main() { if (isMainThread) { mainDo(); } else { clusterDo(); } }
main();
|