手把手带你开发一个node切换源小工具

广告:宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取~~~

手把手带你开发一个node切换源小工具

node怎么切换源?下面本篇文章带大家手搓一个node切换源小工具,希望对大家有所帮助!

嗨嗨嗨,又到了写轮子环节了,为什么要写这个东西呢?

应为npm自带的源下载东西灰常慢

目前已经有一款工具了nrm 也是做切换源的 例如tabao源,腾讯源,下载依赖包的时候能加速,那有这么多的源nrm可以帮我们管理起来随时切换。

第一个朋友安装nrm很麻烦还需要用源码的方式安装

第二个朋友公司私服多,自己又懒得手动切换

于是我们想自己写一个小工具实现简易的切换npm源 【相关教程推荐:nodejs视频教程】

思路1,调用命令 设置源

npm config set registry  源地址
登录后复制

思路2 使用查看命令获取源地址

npm config get registry
登录后复制

主要就是这两步操作

代码实现

commander

commander是一个nodejs的模块可以解析我们输入的命令,常用于各种脚手架如vue vite等,

例如 xxx -V查看版本 xxx use执行脚本 xxx -h查看帮助 等都可以使用 commander实现

inquirer

inquirer也是nodejs的一个模块,常用于命令交互,如vue的cli,vite等,react脚手架等

例如这种选项,还有输入框,多选等

registries.json

这个文件里面放一些初始的源,从nrm的github偷的ping是我自己加的

{    "npm": {        "home": "https://www.npmjs.org",        "registry": "https://registry.npmjs.org/",        "ping": "https://registry.npmjs.org"    },    "yarn": {        "home": "https://yarnpkg.com",        "registry": "https://registry.yarnpkg.com/",        "ping": "https://registry.yarnpkg.com"    },    "tencent": {        "home": "https://mirrors.cloud.tencent.com/npm/",        "registry": "https://mirrors.cloud.tencent.com/npm/",        "ping": "https://mirrors.cloud.tencent.com/npm"    },    "cnpm": {        "home": "https://cnpmjs.org",        "registry": "https://r.cnpmjs.org/",        "ping": "https://r.cnpmjs.org"    },    "taobao": {        "home": "https://npmmirror.com",        "registry": "https://registry.npmmirror.com/",        "ping": "https://registry.npmmirror.com"    },    "npmMirror": {        "home": "https://skimdb.npmjs.com/",        "registry": "https://skimdb.npmjs.com/registry/",        "ping": "https://skimdb.npmjs.com/registry"    }}
登录后复制
#!/usr/bin/env nodeconst { program } = require('commander')const PKG = require('../package.json') //引入package jsonconst registries = require('../registries.json'); //引入初始源const inquirer = require('inquirer');const { exec, execSync } = require('child_process') //子线程用于执行shell命令const ping = require('node-http-ping') //ping网址的一个库const fs = require('fs')const chalk = require("chalk"); //console 变颜色的一个库const path = require('path')program.version(PKG.version) //设置版本默认命令 -V --version//读取源地址方便设置*const getOrigin = async () => {    return await execSync('npm get registry', { encoding: "utf-8" })}//列出所有的源,如果当前有在使用前面加上*program.command('ls').description('查看镜像').action(async () => {    const res = await getOrigin()    const keys = Object.keys(registries)    const message = []    //填充横线算法npm------  yarn------    const max = Math.max(...keys.map(v => v.length)) + 3    keys.forEach(k => {        const newK = registries[k].registry == res.trim() ? ('* ' + k) : ('  ' + k)        const Arr = new Array(...newK)        Arr.length = max;        const prefix = Array.from(Arr).map(v => v ? v : '-').join('')        message.push(prefix + '  ' + registries[k].registry)    })    console.log(message.join('\n'))})//切换源program.command('use').description('请选择镜像').action(() => {    inquirer.prompt([        {            type: "list",            name: "sel",            message: "请选择镜像",            choices: Object.keys(registries)        }    ]).then(result => {        const reg = registries[result.sel].registry        exec(`npm config set registry ${reg}`, null, (err, stdout, stderr) => {            if (err) {                console.error('切换错误', err)            } else {                console.log('切换成功')            }        })    })})//获取当前源program.command('current').description('查看当前源').action(async () => {    const reg = await getOrigin()    const v = Object.keys(registries).find(k => {        if (registries[k].registry === reg.trim()) {            return k;        }    })    console.log(chalk.blue('当前源:', v))})//ping 源program.command('ping').description('测试镜像地址速度').action(() => {    inquirer.prompt([        {            type: "list",            name: "sel",            message: "请选择镜像",            choices: Object.keys(registries)        }    ]).then(result => {        const url = registries[result.sel].ping.trim()        ping(url).then(time => console.log(chalk.blue(`响应时长: ${time}ms`)))            .catch(() => console.log(chalk.red('GG')))    })})//添加源 读写registries.json 文件实现program.command('add').description('自定义镜像').action(() => {    inquirer.prompt([        {            type: "input",            name: "name",            message: "请输入镜像名称",            validate(answer) {                const keys = Object.keys(registries)                if (keys.includes(answer)) {                    return `不能起名${answer}跟保留字冲突`                }                if (!answer) {                    return '名称不能为空'                }                return true            }        },        {            type: "input",            name: "url",            message: "请输入镜像地址",            validate(answer) {                if (!answer) {                    return `url不能为空`                }                return true            }               }    ]).then(result => {        const del = (url) => {            const arr = url.split('')            //本来想用at 16 以下不支持            return arr[arr.length - 1] == '/' ? (arr.pop() && arr.join('')) : arr.join('')        }        registries[result.name] = {            home: result.url.trim(),            registry: result.url.trim(),            ping: del(result.url.trim()), //去掉末尾/ 不然无法ping        }        fs.writeFileSync(path.join(__dirname, '../registries.json'), JSON.stringify(registries, null, 4))        console.log(chalk.blue('添加完成'))    })})program.parse(process.argv)
登录后复制

使用方式

npm i xmzs -g
登录后复制

安装完之后会有一个mmp 命令为什么不叫xmzs 别问问就是喜欢mmp

mmp ls
登录后复制

列出所有的源

mmp use
登录后复制

切换源 nrm是输入,我这儿是选择框方便一些

mmp current
登录后复制

查看当前源

mmp ping
登录后复制

测速

map add
登录后复制

自定义源

mmp ls 查看

更多node相关知识,请访问:nodejs 教程!

以上就是手把手带你开发一个node切换源小工具的详细内容,更多请关注9543建站博客其它相关文章!

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。
作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:超链接怎么做
下一篇:uniapp能做小游戏吗?

发表评论

关闭广告
关闭广告