Nrm 是 Node.js 的鏡像管理小工具,可以方便地查看鏡像源列表和管理這些鏡像源,并且可以快速地切換到最適合當(dāng)前網(wǎng)絡(luò)環(huán)境的鏡像源。

背景
很多開發(fā)者會(huì)遇到這樣的情況,Node安裝包的時(shí)候,國內(nèi)鏡像源有些包安裝不上,需要更換為淘寶鏡像源,而有些包在淘寶鏡像源又下載不到,導(dǎo)致需要每次重新設(shè)置鏡像源,以至于下次都不知道當(dāng)前使用的哪個(gè)鏡像源故該管理工具出現(xiàn),極大便利了我們的開發(fā)
1、nrm 介紹
nrm 是 Node.js 的鏡像管理小工具,可以方便地查看鏡像源列表和管理這些鏡像源,并且可以快速地切換到最適合當(dāng)前網(wǎng)絡(luò)環(huán)境的鏡像源。
2、安裝
全局安裝 npm i nrm -g。
3、常用命令
「查看」當(dāng)前可用的鏡像源列表:nrm ls。

「切換」鏡像源 :nrm use <registry> 或 nrm use <url>。
- <registry> 是鏡像源名稱,<url> 是鏡像源的地址。
- 例如切換到淘寶:nrm use taobao 或 nrm use https://registry.npm.taobao.org/。
「添加」新的鏡像源:nrm add <registry> <url>。
- 例如:nrm add test http://test.com/。
「刪除」鏡像源 :nrm del <registry>。
「測試」鏡像源速度:nrm test。
「顯示」當(dāng)前使用的鏡像源:nrm current。
- 查看源列表時(shí),當(dāng)前源的名稱前面帶*號(hào),也可以用于查看當(dāng)前鏡像源。
打開指定鏡像源的「網(wǎng)站首頁」:nrm home <registry>。
顯示 nrm 命令的「幫助信息」:nrm help。
4、常見報(bào)錯(cuò)
nrm ls 報(bào)錯(cuò)如下:

原因:由于 nrm 的依賴模塊 open 采用的是 ES Module 的方式,但是 nrm 自身是一個(gè) CommonJS 模塊,無法直接加載 ES
Module 的依賴。
解決:先注釋掉報(bào)錯(cuò)文件的第9行(按照路徑查找文件,如果使用的編輯器終端可以用 ctrl + 鼠標(biāo)左鍵 點(diǎn)擊報(bào)錯(cuò)文件直接跳轉(zhuǎn)),再將
require('open') 改為 import('open'),具體修改如下:
// 找到 onHome 函數(shù)并修改
// 源代碼
function onHome (name, browser) {
var allRegistries = getAllRegistry();
var home = allRegistries[name] && allRegistries[name].home;
if (home) {
var args = [home];
if (browser) args.push(browser);
open.apply(null, args);
}
}
// 修改為
function onHome(name, browser) {
var allRegistries = getAllRegistry();
var home = allRegistries[name] && allRegistries[name].home;
if (home) {
var args = [home];
if (browser) args.push(browser);
import('open')
.then((module) => {
var open = module.default;
open(...args);
})
.catch((error) => {
console.error(error);
});
}
}
nrm ls 顯示鏡像源列表后,當(dāng)前源的前面不帶* 號(hào)。
- 再次打開剛才的cli.js文件,修改代碼如下,把&&修改為||,具體如下:
// 源代碼
config(attrs, registry).then(() => {
console.log(' ');
const newR = npm.config.get(FIELD_REGISTRY);
var customRegistries = getCustomRegistry();
Object.keys(customRegistries).forEach(key => {
delete customRegistries[key][FIELD_IS_CURRENT];
});
if (hasOwnProperty(customRegistries, name) && (name in registries || customRegistries[name].registry === registry.registry)) {
registry[FIELD_IS_CURRENT] = true;
customRegistries[name] = registry;
}
setCustomRegistry(customRegistries);
printMsg(['', ' Registry has been set to: ' + newR, '']);
}).catch(err => {
exit(err);
})
// 修改后
config(attrs, registry).then(() => {
console.log(' ');
const newR = npm.config.get(FIELD_REGISTRY);
var customRegistries = getCustomRegistry();
Object.keys(customRegistries).forEach(key => {
delete customRegistries[key][FIELD_IS_CURRENT];
});
if (hasOwnProperty(customRegistries, name) || (name in registries || customRegistries[name].registry === registry.registry)) {
registry[FIELD_IS_CURRENT] = true;
customRegistries[name] = registry;
}
setCustomRegistry(customRegistries);
printMsg(['', ' Registry has been set to: ' + newR, '']);
}).catch(err => {
exit(err);
})