1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| const fs = require('fs'); const https = require('https'); const path = require('path');
const folderPath = './dependency-tars';
if (!fs.existsSync(folderPath)) { fs.mkdirSync(folderPath); }
fs.readFile('package-lock.json', 'utf8', (err, data) => { if (err) { console.error('读取文件出错:', err); return; }
try { const packageLock = JSON.parse(data); const dependencies = packageLock.packages; const tarballUrls = [];
for (const packageName in dependencies) { if (packageName && dependencies.hasOwnProperty(packageName)) { const dependency = dependencies[packageName]; const resolved = dependency.resolved; tarballUrls.push(resolved); } }
console.log(`解析完毕,共${tarballUrls.length}个依赖,开始下载依赖`);
downloadFiles(tarballUrls);
} catch (error) { console.error('解析JSON出错:', error); } });
function downloadFiles(urls) { let count = 0;
for (const url of urls) { const fileName = path.basename(url); const filePath = path.join(folderPath, fileName);
const file = fs.createWriteStream(filePath); https.get(url, (response) => { if (response.statusCode === 200) { response.pipe(file); console.log(`${fileName}下载成功!`);
count++;
if (count === urls.length) { console.log('所有文件下载完成。'); } } else if (response.statusCode === 301 || response.statusCode === 302) { const redirectUrl = response.headers.location; console.log(`文件${fileName}发生重定向,新的下载链接为: ${redirectUrl}`);
https.get(redirectUrl, (redirectResponse) => { redirectResponse.pipe(file); console.log(`${fileName}下载成功!`);
count++;
if (count === urls.length) { console.log('所有文件下载完成。'); } }).on('error', (error) => { console.error(`下载${fileName}出错: ${error.message}`); }); } else { console.error(`下载${fileName}出错,状态码为: ${response.statusCode}`); } }).on('error', (error) => { console.error(`下载${fileName}出错: ${error.message}`); }); } }
|