-
Notifications
You must be signed in to change notification settings - Fork 0
/
n-use.js
196 lines (180 loc) · 5.91 KB
/
n-use.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
const assert = require('node:assert');
const child_process = require('node:child_process');
const fs = require('node:fs');
const https = require('node:https');
const os = require('node:os');
const path = require('node:path');
const { nuseInitRegistry, nodeDistUrl, nuseDirFile } = process.env;
const [versionArg] = process.argv.splice(2);
const cwd = __dirname;
const vfile = path.join(cwd, 'v.html');
const codenNames = {
argon: 4,
boron: 6,
carbon: 8,
dubnium: 10,
erbium: 12,
fermium: 14,
gallium: 16,
hydrogen: 18,
iron: 20,
jod: 22
};
Promise.resolve().then(exec).catch(e => {
console.error(`\x1b[31m${e.message || e}\x1b[0m`);
process.exit(1);
});
async function exec() {
if (!(/win/i.test(os.platform())))
assert.fail(`for non Windows platforms use nvm instead`);
if (nuseInitRegistry)
await initRegistry();
if (!versionArg || versionArg === '-h')
assert.fail(`\x1b[31mUSAGE: nuse number | semver | friendly-name | -v | -h\x1b[0m`);
let nodePath = '';
if (versionArg === '-v') {
nodePath = await execCmd('reg', 'query', 'HKCU\\Environment', '/v', 'nodeDir')
.then(x => x.trim().split(/\s{4}/g)[3]);
} else {
const matchedVersion = await getMatchedVersion();
const versionArch = `node-${matchedVersion}-win-x64`;
nodePath = path.join(cwd, versionArch);
if (!fs.existsSync(nodePath)) {
if (!fs.existsSync(`${nodePath}.zip`)) {
console.info(`downloading ${nodeDistUrl}/${matchedVersion}/${versionArch}.zip ...`);
await downloadBinary(`${nodeDistUrl}/${matchedVersion}/${versionArch}.zip`, `${nodePath}.zip`);
}
console.info(`unpacking ${versionArch}.zip ...`);
await execCmd('tar', '-xf', `${nodePath}.zip`, '-C', cwd);
fs.rmSync(`${nodePath}.zip`, { force: true });
}
}
fs.writeFileSync(nuseDirFile, nodePath, { encoding: 'utf-8' });
}
/**
* Exec cmd in current dir
* @param {string} cmd
* @param {...string} args
* @returns {Promise<string>} Promise<string> stdOut
*/
function execCmd(cmd, ...args) {
return new Promise((ok, rej) => child_process.execFile(
cmd,
args,
{ shell: false },
(err, out) => err ? rej(err) : ok(String(out).trim())
));
}
/**
* Add nuse and node binary path placeholders to user evn
* @returns {Promise<void>} Promise<void>
*/
async function initRegistry() {
const userPath = await execCmd('reg', 'query', 'HKCU\\Environment', '/v', 'Path')
.then(x => x.trim().split(/\s{4}/g)[3]);
let addReg = '';
if (!(/%nuseDir%;/i.test(userPath)))
addReg += '%nuseDir%;';
if (!(/%nodeDir%;/i.test(userPath)))
addReg += '%nodeDir%;';
if (addReg)
await execCmd('reg', 'add', 'HKCU\\Environment', '/t', 'REG_EXPAND_SZ', '/f', '/v', 'Path', '/d', `${userPath}${addReg}`);
}
/**
* Get exact or highest aproximate version
* @returns {Promise<string>} stirng
*/
async function getMatchedVersion() {
if (!fs.existsSync(vfile))
await getVfile();
let ret = findMatchedVersion();
if (!ret) {
const recent = new Date();
recent.setHours(recent.getHours() - 8);
if (fs.statSync(vfile).mtime < recent)
await getVfile();
ret = findMatchedVersion();
}
return ret ?? assert.fail('version not found');
}
/**
* Save Node.js downloads page to disk
* @returns {Promise<void>} Promise<void>
*/
async function getVfile() {
console.info(`querying node versions from ${nodeDistUrl}/ ...`);
const html = await downloadText(`${nodeDistUrl}/`);
fs.writeFileSync(vfile, html, { encoding: 'utf-8' });
}
/**
* Find exact or highest aproximate version
* @returns {string | undefined} string | undefined
*/
function findMatchedVersion() {
const codeName = codenNames[versionArg] || versionArg;
const versions = getHtmlLinks(fs.readFileSync(vfile, { encoding: 'utf-8' }))
.filter(x => /^v\d+\.\d+\.\d+\/$/.test(x))
.map(x => x.replace(/\/$/, ''))
.sort((a, b) => {
a = a.replace(/^v/g, '').split('.').map(n => +n);
b = b.replace(/^v/g, '').split('.').map(n => +n);
if (a[0] > b[0]) return -1;
if (a[0] - b[0]) return 1;
if (a[1] > b[1]) return -1;
if (a[1] - b[1]) return 1;
if (a[2] > b[2]) return -1;
if (a[2] - b[2]) return 1;
return 0;
});
const exact = versions.find(x => new RegExp(`^v${codeName}$`, 'i').test(x));
if (exact) return exact;
const aprox = versions.find(x => new RegExp(`^v${codeName}`, 'i').test(x));
return aprox;
}
/**
* Get list of HTML anchor text
* @param {string} html
* @returns {string[]} string[]
*/
function getHtmlLinks(html) {
return html
.split(/[\r\n]/g)
.reduce((p, t) => {
t = ((t
.split(/<a href=\".+\">/i)[1] || '')
.split(/<\/a>/i)[0] || '')
.trim();
if (t) p.push(t);
return p;
}, []);
}
/**
* Download binary and write to file
* @param {string | URL} url
* @param {string | fs.PathLike} file
* @returns {Promise<void>} Promise<void>
*/
function downloadBinary(url, file) {
return new Promise((ok, rej) => https.get(url, res => {
const sw = fs.createWriteStream(file);
res.pipe(sw);
sw.on('error', err => rej(err));
sw.on('finish', () => sw.close(err => err ? rej(err) : ok()));
}));
}
/**
* Download data as text
* @param {string | URL} url
* @returns {Promise<string>} Promise<string>
*/
function downloadText(url) {
return new Promise((ok, rej) => {
const req = https.get(url, res => {
let data = '';
res.on('data', chunk => data += String(chunk));
res.on('close', () => ok(data));
});
req.on('error', err => rej(err));
req.end();
});
}