-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
extract-js-strings.js
executable file
·84 lines (69 loc) · 1.81 KB
/
extract-js-strings.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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
let DEBUG = false; // Initial debug state
function displayUsage(scriptName) {
console.log(`Usage: ${scriptName} <file-path>
Options:
--debug Enable debug mode.
-h, --help Display this usage information.`);
}
function parseCommandLineArguments() {
const scriptName = path.basename(process.argv[1]);
const args = process.argv.slice(2);
if (args.includes('-h') || args.includes('--help')) {
displayUsage(scriptName);
process.exit(0);
}
const debugFlagIndex = args.indexOf('--debug');
if (debugFlagIndex !== -1) {
DEBUG = true;
args.splice(debugFlagIndex, 1);
}
if (args.length !== 1) {
displayUsage(scriptName);
console.error('\nError: Invalid number of arguments provided.');
process.exit(1);
}
const filePath = args[0];
let code;
try {
code = fs.readFileSync(filePath, 'utf8');
} catch (err) {
console.error(`Error reading file: ${filePath}\n${err.message}`);
process.exit(1);
}
return { code };
}
function parseCodeToAST(code) {
return parser.parse(code, {
sourceType: 'module',
});
}
function extractStrings(ast) {
const strings = [];
traverse(ast, {
StringLiteral: ({ node }) => {
strings.push(node.value);
},
TemplateLiteral: ({ node }) => {
node.quasis.forEach((element) => {
strings.push(element.value.cooked);
});
},
});
return strings;
}
function main() {
const { code } = parseCommandLineArguments();
const ast = parseCodeToAST(code);
const strings = extractStrings(ast);
if (DEBUG) {
console.log('[DEBUG] Extracted Strings:', strings);
} else {
console.log(strings.join('\n'));
}
}
main();