惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Cloudflare Blog
小众软件
小众软件
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
博客园 - 司徒正美
V
Visual Studio Blog
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客
aimingoo的专栏
aimingoo的专栏
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
D
Docker
Vercel News
Vercel News
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
爱范儿
爱范儿
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏

Coding Your Life

lib库开发的一款PDF处理小工具 | Coding Your Life 最长递增子序列算法 | Coding Your Life webpack5 模块联邦技术 | Coding Your Life webpack基础配置详解 | Coding Your Life canvas实现代码雨效果 | Coding Your Life 使用MessageChannel模拟React优先级执行队列 | Coding Your Life vue3 和 react 虚拟dom | Coding Your Life ES6中Reflect对象与Proxy结合实现代理和响应式编程 | Coding Your Life 前端技术分享MediaRecord实现运动相机 | Coding Your Life react基础概念 | Coding Your Life 微信小程序使用canvas创建像素头像 | Coding Your Life 前端基础概念 | Coding Your Life 中高级前端须注意的40条移动端H5坑位指南 | Coding Your Life native-code-push 热更新配置 | Coding Your Life Git 常用命令速查表 | Coding Your Life push-server 热更新常用命令速查表 | Coding Your Life 高效的js片段 | Coding Your Life
mirror-cli | Coding Your Life
Sir_Liu · 2025-05-28 · via Coding Your Life

在使用nodejs时,对镜像源的管理往往需要手动配置,有时候需要记忆复杂而冗长的源链接,这个工具将支持常见镜像源(如官方、淘宝、华为等)的本地配置,你可以为每个镜像源设置一个简单好记的名称,还可以测试镜像源的速度,方便选择最优的镜像源,本工具同时提供了简洁易用的交互界面,方便大家日常使用。

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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#!/usr/bin/env node
import { program } from 'commander';
import inquirer from 'inquirer';
import fs from 'node:fs';
import { execSync } from 'node:child_process';
import path from 'node:path';
import axios from 'axios';
import ora from 'ora';
import chalk from 'chalk';
const { existsSync, readFileSync, writeFileSync } = fs;
const { join } = path;

const CONFIG_PATH = join(process.env.HOME || process.env.USERPROFILE, '.npm-mirror.json');

const DEFAULT_MIRRORS = {
npm: {
registry: 'https://registry.npmjs.org',
home: 'https://www.npmjs.com',
description: '官方 NPM 镜像'
},
taobao: {
registry: 'https://registry.npmmirror.com',
home: 'https://npmmirror.com',
description: '淘宝 NPM 镜像,国内推荐'
},
huawei: {
registry: 'https://mirrors.huaweicloud.com/repository/npm/',
home: 'https://developer.huawei.com',
description: '华为 NPM 镜像'
},
cnpm: {
registry: 'https://r.cnpmjs.org',
home: 'https://cnpmjs.org',
description: 'cnpm 镜像'
}
};


function readConfig() {
if (existsSync(CONFIG_PATH)) {
try {
return JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
} catch (error) {
console.error(chalk.red('配置文件解析失败,将使用默认配置'));
}
}
return { current: 'npm', mirrors: DEFAULT_MIRRORS };
}


function saveConfig(config) {
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
}


function getCurrentMirror(config) {
return config.mirrors[config.current] || config.mirrors.npm;
}


function setMirror(name, config) {
if (!config.mirrors[name]) {
console.error(chalk.red(`镜像源 ${name} 不存在`));
return false;
}

try {
execSync(`npm config set registry ${config.mirrors[name].registry}`);
config.current = name;
saveConfig(config);
console.log(chalk.green(`✅ 已成功将镜像源设置为 ${name}`));
return true;
} catch (error) {
console.error(chalk.red(`设置镜像源失败: ${error.message}`));
return false;
}
}
const config = readConfig();

async function testMirrorSpeed(registry) {
const testUrl = `${registry}/react/latest`;
const spinner = ora(`正在测试 ${registry} 速度...`).start();
try {
const start = Date.now();
await axios.head(testUrl, { timeout: 5000 });
const end = Date.now();
const time = end - start;
spinner.succeed(`测试完成: ${registry} - ${time}ms`);
return time;
} catch (error) {
spinner.fail(`测试失败: ${registry} - ${error.message}`);
return Infinity;
}
}


function listMirrors() {
console.log(chalk.bold('\n可用镜像源列表:\n'));
Object.entries(config.mirrors).forEach(([name, mirror]) => {
const isCurrent = name === config.current;
const prefix = isCurrent ? chalk.green('* ') : ' ';
console.log(`${prefix}${chalk.cyan(name)} - ${mirror.description}`);
console.log(` ${chalk.gray('registry:')} ${mirror.registry}`);
console.log(` ${chalk.gray('home:')} ${mirror.home}\n`);
});
}


function showCurrentMirror() {
const current = getCurrentMirror(config);
console.log(chalk.cyan(`当前使用的镜像源: ${config.current}`));
console.log(chalk.gray(`registry: ${current.registry}`));
console.log(chalk.gray(`home: ${current.home}`));
}


function addCustomMirror(name, registry, home = '无', description = '自定义镜像源') {
if (!name || !registry) {
console.log(chalk.red('请输入正确的镜像源信息'));
return;
}
if (config.mirrors[name]) {
console.log(chalk.red(`镜像源 ${name} 已存在`));
return;
}
config.mirrors[name] = { registry, home, description };
saveConfig(config);
console.log(chalk.green(`✅ 已添加镜像源 ${name}`));
}


async function testMirror() {
console.log(chalk.bold('\n正在测试所有镜像源速度...\n'));
const results = [];

for (const [name, mirror] of Object.entries(config.mirrors)) {
const time = await testMirrorSpeed(mirror.registry);
results.push({ name, time });
}

console.log(chalk.bold('\n测试结果(按速度排序):\n'));
results.sort((a, b) => a.time - b.time).forEach(({ name, time }, index) => {
const isCurrent = name === config.current;
const prefix = isCurrent ? chalk.green('* ') : ' ';
const timeStr = time === Infinity ? '超时' : `${time}ms`;
const rank = index + 1;
console.log(`${prefix}${rank}. ${chalk.cyan(name)} - ${timeStr}`);
});
}

async function main() {
program
.version('1.0.0')
.description('NPM 镜像源管理工具');

program
.command('list')
.description('列出所有可用镜像源')
.action(listMirrors);

program
.command('use <name>')
.description('切换到指定镜像源')
.action((name) => {
setMirror(name, config);
});

program
.command('current')
.description('查看当前使用的镜像源')
.action(showCurrentMirror);

program
.command('add <name> <registry> [home] [description]')
.description('添加自定义镜像源')
.action(addCustomMirror);

program
.command('delete <name>')
.description('删除镜像源')
.action((name) => {
if (name === 'npm' || name === 'taobao') {
console.error(chalk.red('不能删除内置镜像源'));
return;
}

if (!config.mirrors[name]) {
console.error(chalk.red(`镜像源 ${name} 不存在`));
return;
}

if (config.current === name) {
config.current = 'npm';
}

delete config.mirrors[name];
saveConfig(config);
console.log(chalk.green(`✅ 已删除镜像源 ${name}`));
});

program
.command('test')
.description('测试所有镜像源速度')
.action(testMirror);

program
.command('interactive')
.description('交互式界面')
.action(async () => {
const { action } = await inquirer.prompt([{
type: 'list',
name: 'action',
message: '请选择操作:',
choices: [
'查看当前镜像源',
'列出所有镜像源',
'切换镜像源',
'添加自定义镜像源',
'测试镜像源速度',
'退出'
]
}]);

switch (action) {
case '查看当前镜像源':
showCurrentMirror();
break;
case '列出所有镜像源':
listMirrors();
break;
case '切换镜像源':
const { mirror } = await inquirer.prompt([{
type: 'list',
name: 'mirror',
message: '选择要使用的镜像源:',
choices: Object.keys(config.mirrors)
}]);
setMirror(mirror, config);
break;
case '添加自定义镜像源':
const answers = await inquirer.prompt([
{ type: 'input', name: 'name', message: '镜像源名称:' },
{ type: 'input', name: 'registry', message: 'registry 地址:' },
{ type: 'input', name: 'home', message: '主页地址:' },
{ type: 'input', name: 'description', message: '描述信息:' }
]);
addCustomMirror(answers.name, answers.registry, answers.home, answers.description);
break;
case '测试镜像源速度':
testMirror();
break;
case '退出':
console.log(chalk.yellow('👋 再见!'));
break;
}
});


if (process.argv.length < 3) {
program.help();
} else {
program.parse(process.argv);
}
}

main();