美文网首页
内网环境怎么解决npm包的批量下载和往npm私有仓库批量上传tg

内网环境怎么解决npm包的批量下载和往npm私有仓库批量上传tg

作者: videring | 来源:发表于2021-06-26 01:33 被阅读0次

背景:内网环境基于nexus搭建好了npm仓库,但是没有任何办法连接互联网。

痛点:前端项目依赖多且碎,怎么解决npm包批量下载和上传到私有仓库的问题?

解决方案

  • 基于npm view及递归算法命令获取依赖包列表或基于--package-lock-only生成pack-lock.json文件从中读取依赖包列表
  • 基于npm pack下载tgz格式的依赖
  • 基于npm publish上传依赖到内网仓库或基于nexus api上传。

一、在互联网环境下载

1.1 基于npm view及递归算法命令获取依赖包列表或基于--package-lock-only生成pack-lock.json文件从中读取依赖包列表;

  • 先建立download/downloaded目录,download用于放下载好的文件,download/downloaded用于放之前下载好的文件,避免重复下载。
  • 通过npm安装shelljs、json5

1.2 遍历上一步的依赖列表,基于npm pack命令,逐个下载。

参考代码如下:

const shell = require('shelljs');
const JSON5 = require('json5');
const { exec } = require('child_process');
const fs = require("fs");

function download(fileNames = []) {
    shell.cd('download');
    let count = 0;
    fileNames.forEach(fileName => {
        // shell.echo(`>>> 正在下载 ${fileName}...`);
        const fileExec = shell.exec(`npm pack ${fileName}`, { async: true, silent: true});
        fileExec.stdout
            .on('data', () => {
                ++count;
                shell.echo(`>>> ${fileName} 下载完成...`);
                if (count === fileNames.length) {
                    shell.cd('..');
                    shell.exit(0);
                }
            })
            .on('err', () => {
                ++count
                shell.echo(`>>> ${fileName} 下载失败!!!...`);
                if (count === fileNames.length) {
                    shell.cd('..');
                    shell.exit(0);
                }
            })
    })
}

/*
* param packageNameOrWidthVersion,形如react、react@^16.13.0都可以,遵守npm规范即可
* */
function downloadNpm(packageNameOrWidthVersion) {
    const nMap = new Map();

    function getAllList(pkg) {
        if (nMap.has(pkg) || !pkg) {
            return
        }
        nMap.set(pkg, true);

        // 寻找依赖
        const execLine = `npm view ${pkg} dependencies --json`;
        const execResult = shell.exec(execLine, { async: false, silent: true });

        let deps;
        try {
            if (execResult.stdout) {
                deps = JSON5.parse(execResult.stdout);
                /*
                * {"loose-envify": "^1.1.0", "object-assign": "^4.1.1", "prop-types": "^15.6.2"} 转换成
                * ["loose-envify^1.1.0", "object-assign^4.1.1", "prop-types^15.6.2"]
                */
                let depPackages = [];
                if (Array.isArray(deps)) {
                    deps.forEach(dep => {
                        if (Object.prototype.toString.apply(dep) === '[object Object]') {
                            depPackages.push(...Object.keys(dep).map(d => dep[d].includes(' ') ? `${d}@'${dep[d]}'` : `${d}@${dep[d]}`));
                        }
                    })
                } else if (Object.prototype.toString.apply(deps) === '[object Object]') {
                    depPackages = Object.keys(deps).map(dep => deps[dep].includes(' ') ? `${dep}@'${deps[dep]}'` : `${dep}@${deps[dep]}`);
                }
                
                depPackages.forEach(dep => {
                    getAllList(dep);
                })
            }
        } catch (e) {
            console.debug('getAllList ', pkg, '的dependencies下载报错:', e);
        }
    }

    getAllList(packageNameOrWidthVersion);
    shell.echo(`一共${Array.from(nMap.keys()).length}个依赖包待下载\n`)
    shell.echo(`>>> 待下载列表: \n - ${Array.from(nMap.keys()).join('\n - ')}...`);
    download(Array.from(nMap.keys()));
}

function downloadByPackageJsonLockFile(depLockJsonFile = {}) {
    const nMap = new Map();
    const NotMap = new Map();
    const downloadedDir = './download/downloaded'; // 每次下载的文件会放在download里,publish到仓库后,可以手动移动到download/downloaded里,方便下次避免重复下载
    const downloadedArr = fs.readdirSync(downloadedDir);

    function getAllList(depJson) {
        if (depJson) {
            Object.keys(depJson).forEach(dep => {
                const depWithVersion = `${dep}@${depJson[dep].version}`;
                let tgzFormat = `${dep}-${depJson[dep].version}.tgz`;
                // eg: @babel/code-frame-7.14.5.tgz -> babel-code-frame-7.14.5.tgz
                tgzFormat = dep.startsWith('@') ? tgzFormat.split('/').join('-').slice(1) : tgzFormat
                if (!nMap.has(depWithVersion) && !downloadedArr.includes(tgzFormat)) {
                    nMap.set(depWithVersion, true);
                    getAllList(depJson[dep].dependencies);
                } else if (downloadedArr.includes(tgzFormat) && !NotMap.has(tgzFormat)) {
                    NotMap.set(tgzFormat, true);
                }   
            })
        }
    }

    getAllList(depLockJsonFile.dependencies);
    shell.echo(`一共${Array.from(NotMap.keys()).length}个依赖包已在${downloadedDir}目录下存在,不需要重复下载:\n`);
    shell.echo(`>>> 无需下载列表: \n - ${Array.from(NotMap.keys()).join('\n - ')}...\n`);
    shell.echo(`一共${Array.from(nMap.keys()).length}个依赖包待下载\n`)
    shell.echo(`>>> 待下载列表: \n - ${Array.from(nMap.keys()).join('\n - ')}...`);
    download(Array.from(nMap.keys()));
}

/*
* 方式一:通过具体npm包下载相关依赖
*/
// downloadNpm('node-nightly@^1.7.3');

/*
* 建议用这种方式,简单、快捷、错误少(将node-nightly@^1.7.3替换成需要的依赖和版本号即可)
* 方式二:通过生成package-lock.json下载所有依赖--package-lock-only
*/
exec('npm i node-nightly@^1.7.3 --package-lock-only', (error, stdout, stderror) => {
    if (error) {
        console.error('package-lock.json文件生成失败...')
        return
    }
    const pkgLock = require('./package-lock');
    downloadByPackageJsonLockFile(pkgLock);
})

二、上传

利用npm publish命令上传

  • 执行npm adduser命令,输入私有仓库的账号和密码;

  • 遍历1.2节中下载的tgz文件,利用npm publish上传文件,如:

/*
* 请先确保执行了npm adduser操作
* filesDir是文件下载目录,跟脚本在同一级,目录中的文件就是待publish到私有仓库的文件
*/
let fs = require('fs');
let path = require('path');
const {exec} = require('child_process');
const publishPosition = 'npm publish --registry=http://某ip:某port/repository/某目录'; // 前端仓库地址
const filesDir = '../download/'; // 待publish文件地址
fs.readdir(filesDir, (errs, files) => {
    files.forEach(file => {
        fs.stat(filesDir + file, function(err, stats) {
            if (stats.isFile()) {
                const fullFilePath = path.resolve(__dirname, filesDir + file)
                console.log(fullFilePath + ' publish 开始')
                exec(publishPosition + ' ' + fullFilePath, function(error, stdout, stderr) {
                    if (error) {
                        console.error(fullFilePath + ' publish 失败')
                    } else {
                        console.error(fullFilePath + ' publish 成功')
                    }
                })
            }
        })
    })
})

需要注意的是,执行npm publish可能会报跟nexus相关的权限、策略方面的问题,基本百度下就可以修改好了。

利用 nexus rest API上传

此方法似乎更快,尤其是大批量的。

#!/bin/bash
targetDir=tgz文件所在目录
publishRestful=ip地址:port端口/service/rest/v1/components?repository=npm仓库名
echo ">>> 文件所在目录:$targetDir <<<"
dir=$(ls -l $targetDir | awk '/.tgz$/ {print $NF}')
cd $targetDir

for file in $dir
do
  echo ">>> $targetDir/$file 上传开始 \n"
  ret=`curl -u nexus用户名:nexus密码 -X POST "$publishRestful" -H "Accept: application/json" -H "Content-Type: multipart/form-data" -F "npm.asset=@$file;type=application/x-compressed"`
  echo $ret
  echo ">>> $targetDir/$file 上传完成 \n"
done

核心命令:curl -u user:password -X POST "http://localhost:8081/service/rest/v1/components?repository=npm-private" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "npm.asset=@my-npm-package-0.0.0.tgz;type=application/x-compressed"

!!!考虑到上述方法会重复上传仓库中已存在的依赖,下面给出了另一套方案

  • 利用axios,调用nexus /service/rest/v1/components GET接口获取仓库所有依赖
  • 获取待上传的tgz文件,并依据上一步的结果过滤掉不需要重复上传的tgz
  • 用nexus /service/rest/v1/components POST接口上传tgz文件
let fs = require('fs');
let path = require('path');
const {exec} = require('child_process');
const axios = require('axios');

const needToUploadFilesDir = '../download'; // 自定义,待上传tgz文件所在目录
const publishRestful = 'nexus的IP:PORT/service/rest/v1/components?repository=仓库名';

// 保存nexus仓库已有依赖
const existItems= [];

const excludeExistedFiles = () => {
    fs.readdir(needToUploadFilesDir, (err, files) => {
        console.log('》》》2.上传tgz《《《')
        files.filter(f => !existItems.includes(f)).forEach(f => {
            const file = f; // path.resolve(needToUploadFilesDir, f);
            const curlCmd = `curl -u 登录名:登录密码 -X POST \"${publishRestful}\" -H "Accept: application/json" -H "Content-Type:multipart/form-data" -F "npm.asset=@${file};type=application/x-compressed"`;

            exec(curlCmd, {cwd: needToUploadFilesDir}, function (error, stdout, stderr) {
                if (error) {
                    console.error(file + ' publish 失败');
                    console.log(error);
                } else {
                    console.log(file + ' publish 成功', stdout)
                }
            });
        })
    })
}

const getReq = async (continuationToken) => {
    const contiToken = continuationToken ? ('&continuationToken=' + continuationToken) : '';
    const result = await axios.get('nexus的IP:PORT/service/rest/v1/components?repository=仓库名' + contiToken);
    if (result.status === 200 && result.data && result.data.items) {
        existItems.push(...result.data.items.map(item => {
            const g = item.group ? (item.group + '-') : '';
            const n = item.name + '-';
            const v = item.version + '.tgz';
            return g + n + v;
        }))

        if (result.data.continuationToken) {
            await getReq(result.data.continuationToken)
        } else {
            console.log('请求结束时间戳: ', new Date().valueOf());
            console.log('请求完毕,结果写入文件中(备用,可忽略) ');
            fs.writeFile(new Date().valueOf() + '.log', JSON.stringify(existItems, null, 2), (err) => {
                console.log('结果写入文件完毕! ! !');
                //借助nexus rest API上传文件
                excludeExistedFiles();
            })
        }
    } else {
        console.log('》》》》请求出现异常《《《');
    }
}

console.log('》》》1.获取仓库中已有依赖,大概需要2~3分钟,请耐心等候..《《《');
console.log('开始请求时间戳: ', new Date().valueOf());
console.log('请求中......');

getReq();


相关文章

网友评论

      本文标题:内网环境怎么解决npm包的批量下载和往npm私有仓库批量上传tg

      本文链接:https://www.haomeiwen.com/subject/wspayltx.html