背景:內(nèi)網(wǎng)環(huán)境基于nexus搭建好了npm倉(cāng)庫,但是沒有任何辦法連接互聯(lián)網(wǎng)逼侦。
痛點(diǎn):前端項(xiàng)目依賴多且碎谚攒,怎么解決npm包批量下載和上傳到私有倉(cāng)庫的問題?
解決方案:
- 基于npm view及遞歸算法命令獲取依賴包列表或基于--package-lock-only生成pack-lock.json文件從中讀取依賴包列表
- 基于npm pack下載tgz格式的依賴
- 基于npm publish上傳依賴到內(nèi)網(wǎng)倉(cāng)庫或基于nexus api上傳曙痘。
一芳悲、在互聯(lián)網(wǎng)環(huán)境下載
1.1 基于npm view及遞歸算法命令獲取依賴包列表或基于--package-lock-only生成pack-lock.json文件從中讀取依賴包列表;
- 先建立download/downloaded目錄边坤,download用于放下載好的文件名扛,download/downloaded用于放之前下載好的文件,避免重復(fù)下載茧痒。
- 通過npm安裝shelljs肮韧、json5
1.2 遍歷上一步的依賴列表,基于npm pack命令,逐個(gè)下載弄企。
參考代碼如下:
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規(guī)范即可
* */
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"} 轉(zhuǎn)換成
* ["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(' ') ? `$uiqetgx@'${dep[d]}'` : `$8dbmq2i@${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下載報(bào)錯(cuò):', e);
}
}
getAllList(packageNameOrWidthVersion);
shell.echo(`一共${Array.from(nMap.keys()).length}個(gè)依賴包待下載\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'; // 每次下載的文件會(huì)放在download里,publish到倉(cāng)庫后圣猎,可以手動(dòng)移動(dòng)到download/downloaded里士葫,方便下次避免重復(fù)下載
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}個(gè)依賴包已在${downloadedDir}目錄下存在,不需要重復(fù)下載:\n`);
shell.echo(`>>> 無需下載列表: \n - ${Array.from(NotMap.keys()).join('\n - ')}...\n`);
shell.echo(`一共${Array.from(nMap.keys()).length}個(gè)依賴包待下載\n`)
shell.echo(`>>> 待下載列表: \n - ${Array.from(nMap.keys()).join('\n - ')}...`);
download(Array.from(nMap.keys()));
}
/*
* 方式一:通過具體npm包下載相關(guān)依賴
*/
// downloadNpm('node-nightly@^1.7.3');
/*
* 建議用這種方式送悔,簡(jiǎn)單慢显、快捷、錯(cuò)誤少(將node-nightly@^1.7.3替換成需要的依賴和版本號(hào)即可)
* 方式二:通過生成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命令上傳
執(zhí)行npm adduser命令荚藻,輸入私有倉(cāng)庫的賬號(hào)和密碼;
遍歷1.2節(jié)中下載的tgz文件跪妥,利用npm publish上傳文件鞋喇,如:
/*
* 請(qǐng)先確保執(zhí)行了npm adduser操作
* filesDir是文件下載目錄声滥,跟腳本在同一級(jí)眉撵,目錄中的文件就是待publish到私有倉(cāng)庫的文件
*/
let fs = require('fs');
let path = require('path');
const {exec} = require('child_process');
const publishPosition = 'npm publish --registry=http://某ip:某port/repository/某目錄'; // 前端倉(cāng)庫地址
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 成功')
}
})
}
})
})
})
需要注意的是,執(zhí)行npm publish可能會(huì)報(bào)跟nexus相關(guān)的權(quán)限落塑、策略方面的問題纽疟,基本百度下就可以修改好了。
利用 nexus rest API上傳
此方法似乎更快憾赁,尤其是大批量的污朽。
- 官網(wǎng)信息見https://help.sonatype.com/repomanager3/rest-and-integration-api/components-api;
- shell腳本如下:
#!/bin/bash
targetDir=tgz文件所在目錄
publishRestful=ip地址:port端口/service/rest/v1/components?repository=npm倉(cāng)庫名
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"
龙考。
s∷痢!晦款!考慮到上述方法會(huì)重復(fù)上傳倉(cāng)庫中已存在的依賴炎功,下面給出了另一套方案
- 利用axios,調(diào)用nexus /service/rest/v1/components GET接口獲取倉(cāng)庫所有依賴
- 獲取待上傳的tgz文件缓溅,并依據(jù)上一步的結(jié)果過濾掉不需要重復(fù)上傳的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=倉(cāng)庫名';
// 保存nexus倉(cāng)庫已有依賴
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=倉(cāng)庫名' + 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('請(qǐng)求結(jié)束時(shí)間戳: ', new Date().valueOf());
console.log('請(qǐng)求完畢,結(jié)果寫入文件中(備用,可忽略) ');
fs.writeFile(new Date().valueOf() + '.log', JSON.stringify(existItems, null, 2), (err) => {
console.log('結(jié)果寫入文件完畢! ! !');
//借助nexus rest API上傳文件
excludeExistedFiles();
})
}
} else {
console.log('》》》》請(qǐng)求出現(xiàn)異秤倨耄《《《');
}
}
console.log('》》》1.獲取倉(cāng)庫中已有依賴股囊,大概需要2~3分鐘,請(qǐng)耐心等候..《《《');
console.log('開始請(qǐng)求時(shí)間戳: ', new Date().valueOf());
console.log('請(qǐng)求中......');
getReq();