脚本意义

在一个组件库的项目中,因为支持单独安装每个组件,因此目录下有多个 package,所以在升级依赖的时候有些重复的操作,如果一个个改太浪费时间了,即使使用lerna run --stream --sort 这种形式,也可能因为一个 package 运行报错导致全部停止,而且第二次运行的时候又得重头来,还是比较浪费时间的

于是就自己写了个脚本,可以多进程同时在多个目录下运行,pnpm 下的命令(当然换成shell也是可以的)

todo

写的时间有点久,有些地方没有写好,比如没有补上 error 的打印,以及下次还是重头来,如果增加每次检查是否有进度文件,等下次用到的时候再优化下。

源码一可以在一个文件里就把主、从进程的逻辑写完,源码二就得单独写个文件了,不过源码一也是比较久之前的代码了,还是以 node 服务为例,

源码一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import cluster from 'cluster';
import os from 'os';
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
for (let i = 0; i < numCPUs; i++) {
​ cluster.fork(); // 创建工作进程
​ }
​ cluster.on('exit', (worker, code, signal) => {
console.log(Worker ${*worker*.process.pid} died);
​ });
} else {
​ http.createServer((req, res) => {
​ res.writeHead(200);
​ res.end('Hello World\n');
​ }).listen(8000);
}

源码二

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();