| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- #!/usr/bin/env node
- /**
- * 从 registry 拉取完整 npm 包并解压到 nodejs/backup/npm(供离线恢复用)
- */
- const fs = require('fs');
- const path = require('path');
- const https = require('https');
- const zlib = require('zlib');
- const NPM_REGISTRY = 'https://registry.npmmirror.com';
- const repoNodejs = __dirname;
- const backupRoot = path.join(repoNodejs, 'backup');
- const npmBackupDir = path.join(backupRoot, 'npm');
- const extractDir = path.join(repoNodejs, 'npm-backup-extract');
- function isNpmBundleComplete(dir) {
- if (!fs.existsSync(path.join(dir, 'bin', 'npm-cli.js'))) return false;
- return fs.existsSync(path.join(dir, 'node_modules', 'graceful-fs', 'package.json'));
- }
- function get(url) {
- return new Promise((resolve, reject) => {
- const req = https.get(url, { headers: { 'User-Agent': 'Node/download-npm-backup' } }, (res) => {
- if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
- const loc = res.headers.location;
- return get(loc.startsWith('http') ? loc : new URL(loc, url).href).then(resolve).catch(reject);
- }
- const chunks = [];
- res.on('data', (c) => chunks.push(c));
- res.on('end', () => resolve(Buffer.concat(chunks)));
- res.on('error', reject);
- });
- req.on('error', reject);
- });
- }
- function extractTar(buffer, outDir) {
- let offset = 0;
- while (offset + 512 <= buffer.length) {
- const header = buffer.slice(offset, offset + 512);
- if (header.every((b) => b === 0)) break;
- const name = header.slice(0, 100).toString('utf8').replace(/\0/g, '');
- const size = parseInt(header.slice(124, 136).toString('utf8').trim(), 8) || 0;
- const typeflag = header[156] && header[156] !== 0 ? String.fromCharCode(header[156]) : '0';
- offset += 512;
- const content = buffer.slice(offset, offset + size);
- offset += Math.ceil(size / 512) * 512;
- if (!name || name.includes('..')) continue;
- const dest = path.join(outDir, name);
- if (typeflag === '5' || name.endsWith('/')) {
- if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
- } else if (size >= 0) {
- const dir = path.dirname(dest);
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(dest, content);
- }
- }
- }
- async function main() {
- fs.mkdirSync(backupRoot, { recursive: true });
- console.log('Fetching npm metadata from registry...');
- const meta = JSON.parse((await get(`${NPM_REGISTRY}/npm/latest`)).toString());
- const version = meta.version;
- const tarball = meta.dist?.tarball || `${NPM_REGISTRY}/npm/-/npm-${version}.tgz`;
- console.log('Downloading npm@' + version + '...');
- const tgz = await get(tarball);
- if (tgz.length < 1000 && tgz.toString().includes('<!')) {
- throw new Error('Registry returned HTML instead of tarball.');
- }
- if (tgz[0] !== 0x1f || tgz[1] !== 0x8b) {
- throw new Error('Downloaded file is not gzip.');
- }
- if (fs.existsSync(extractDir)) {
- try {
- fs.rmSync(extractDir, { recursive: true, force: true });
- } catch (_) {}
- }
- fs.mkdirSync(extractDir, { recursive: true });
- const tar = zlib.gunzipSync(tgz);
- extractTar(tar, extractDir);
- const pkgDir = path.join(extractDir, 'package');
- const unpacked = fs.existsSync(pkgDir) ? pkgDir : path.join(extractDir, fs.readdirSync(extractDir)[0]);
- if (fs.existsSync(npmBackupDir)) {
- console.log('Removing old nodejs/backup/npm...');
- fs.rmSync(npmBackupDir, { recursive: true, force: true });
- }
- fs.renameSync(unpacked, npmBackupDir);
- try {
- fs.rmSync(extractDir, { recursive: true, force: true });
- } catch (_) {}
- if (!isNpmBundleComplete(npmBackupDir)) {
- console.error('[X] Extracted npm backup failed integrity check (missing npm-cli or graceful-fs)');
- process.exit(1);
- }
- console.log('[OK] Full npm@' + version + ' saved to nodejs/backup/npm');
- }
- main().catch((err) => {
- console.error(err);
- process.exit(1);
- });
|