create_key.js
1const args = process.argv.slice(2);
2
3function printUsageAndExit() {
4 console.error('Usage: node create_key.js <length>');
5 console.error(' <length> should be a positive integer, default is 16');
6 process.exit(1);
7}
8
9function validateArgs(args) {
10 if (
11 args.length > 1 ||
12 (args[0] && (args[0] === '-h' || args[0] === '--help'))
13 ) {
14 printUsageAndExit();
15 }
16
17 const length = parseInt(args[0], 10);
18
19 if (args[0] && (isNaN(length) || length <= 0)) {
20 throw new Error('Argument must be a positive integer');
21 }
22
23 return length || 16;
24}
25
26function createKey(length) {
27 const chars =
28 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
29 let key = '';
30
31 for (let i = 0; i < length; i++) {
32 key += chars.charAt(Math.floor(Math.random() * chars.length));
33 }
34
35 return key;
36}
37
38try {
39 const length = validateArgs(args);
40 console.log(createKey(length));
41} catch (error) {
42 console.error(error.message);
43 printUsageAndExit();
44}
45