关于私有源仓库(nexus)无法实时同步npm源的代理问题处理

前言

在官方npm依赖更新后会出现打包失败的问题,一般是由于nexus中配置的代理无法同步引起的。

解决措施

  • (1)固定依赖版本
  • (2)下载最新的依赖包手动上传
  • (3)参照其他版本的依赖包下载上传 形如:https://registry.npmmirror.com/@babel/parser/-/parser-7.18.10.tgz(但这种方法依赖包可能会不全,可尝试)

这里主要分享第二种解决方案。

步骤分解

  • (1) 新建目录 nodejs
  • (2) 运行 npm install package@version --save
  • (3) 执行 python add.py
  • (4) 执行 ./push.sh

//add.py

# -*-coding:utf-8-*-
import json
import os
from pathlib import Path
from urllib.request import urlretrieve
def node_modules(file_dir):
    """  通过递归遍历 node_modules 每个子包的package.json 解析下载链接 """
    links = []
    for root, dirs, files in os.walk(file_dir):
        if 'package.json' in files:
            package_json_file = os.path.join(root, 'package.json')
            try:
                with open(package_json_file, 'r', encoding='UTF-8') as load_f:
                    load_dict = json.load(load_f)
                    # print(load_dict)
                    if '_resolved' in load_dict.keys():
                        links.append(load_dict['_resolved'])
            except Exception as e:
                print(package_json_file)
                print('Error:', e)
    return links
def package_lock(package_lock_path):
    """ 通过递归遍历 package-lock.json 解析下载链接 """
    links = []
    with open(package_lock_path, 'r', encoding='UTF-8') as load_f:
        load_dict = json.load(load_f)
        # print(load_dict)
        search(load_dict, "resolved", links)
    return links
def yarn_lock(package_lock_path):
    """ 通过递归遍历 xxx-yarn.lock 解析下载链接 """
    links = []
    with open(package_lock_path, 'r', encoding='UTF-8') as load_f:
        for line in load_f:
            if line.find('resolved') >= 0:
                line = line.replace('resolved', '')
                url = line.strip().strip('"')
                links.append(url)
    return links
def search(json_object, key, links):
    """  遍历查找指定的key   """
    for k in json_object:
        if k == key:
            links.append(json_object[k])
        if isinstance(json_object[k], dict):
            search(json_object[k], key, links)
        if isinstance(json_object[k], list):
            for item in json_object[k]:
                if isinstance(item, dict):
                    search(item, key, links)
def download_file(path, store_path):
    """ 根据下载链接下载  """
    if store_path is None:
        store_path = 'D:\\node'
    if not Path(store_path).exists():
        os.makedirs(store_path, int('0755'))
    links = []
    if path.endswith("package-lock.json"):
        links = package_lock(path)
    elif path.endswith("yarn.lock"):
        links = yarn_lock(path)
    else:
        links = node_modules(path)
    print("links:" + str(len(links)))
    # print(links)
    for url in links:
        try:
            filename = url.split('/')[-1]
            index = filename.find('?')
            if index > 0:
                filename = filename[:index]
            index = filename.find('#')
            if index > 0:
                filename = filename[:index]
            filepath = os.path.join(store_path, filename)
            if not Path(filepath).exists():
                print("down:" + url)
                urlretrieve(url, filepath)
        except Exception as e:
            print('Error Url:' + url)
            print('Error:', e)
if __name__ == '__main__':
    down_link = "D:\\node\\package-lock.json"
    download_file(down_link,"D:\\node\\nodejs")
    print("ok")

//push.sh

#!/bin/bash
PACKAGE_PATH=./nodejs
REPOSITORY=http://private.nexus.com:8081/repository/npm-group/
npm login --registry=$REPOSITORY
for file in $PACKAGE_PATH/*.tgz; do
 npm publish --registry=$REPOSITORY $file
done
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值