批量下载npm离线安装包
生活随笔
收集整理的這篇文章主要介紹了
批量下载npm离线安装包
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
批量下載npm離線安裝包
上篇講到如何下載npm離線安裝包的幾種思路
https://blog.csdn.net/xinle0320/article/details/124285708
1、批量下載npm離線安裝包
三種方式
- 通過 package.json 的 _resolved屬性鏈接下載
- 通過 package-lock.json 的 resolved屬性鏈接下載
- 本地直接打包方式
1.1分享使用屬性鏈接方式下載,實現批量下載功能
如有疑問歡迎留言,廢話不多說直接貼代碼
# -*-coding:utf-8-*- import json import os from pathlib import Path from urllib.request import urlretrievedef 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 linksdef 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 linksdef 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 linksdef 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:\\nodejs'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)# else:# print("file already exists:", filename)except Exception as e:print('Error Url:' + url)print('Error:', e)if __name__ == '__main__':# down_link = "C:\\Users\\Administrator\AppData\Roaming\\npm\\node_modules"# down_link = "D:\\Git\\vue\\1\package-yarn.lock"# down_link = "D:\\Git\\vue\\node_modules"down_link = "D:\\Git\\vue\\package-lock.json"download_file(down_link,"D:\\nodejs")print("ok")總結
以上是生活随笔為你收集整理的批量下载npm离线安装包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 产品原型设计之总结
- 下一篇: Oracle 12c:配置em,解决em