forked from magicoflolis/Userscript-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
54 lines (46 loc) · 1.6 KB
/
Copy pathindex.js
File metadata and controls
54 lines (46 loc) · 1.6 KB
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
'use strict';
import { readdir, readFile, stat } from 'node:fs/promises';
import { URL, fileURLToPath } from 'node:url';
/**
*
* @type { import('../typings/index.d.ts').loadLanguages }
*/
async function loadLanguages(dir, recursive = true, mapper = new Map()) {
try {
// Get the stats of the directory
const statDir = await stat(dir);
// If the provided directory path is not a directory, throw an error
if (!statDir.isDirectory()) {
throw new Error(`The directory '${dir}' is not a directory.`);
}
// Get all the files in the directory
const files = await readdir(dir);
// Loop through all the files in the directory
for (const file of files) {
// Get the stats of the file
const statFile = await stat(new URL(`${dir}/${file}`));
// If the file is a directory and recursive is true, recursively load the structures in the directory
if (statFile.isDirectory() && recursive) {
await loadLanguages(new URL(`${dir}/${file}`), recursive, mapper);
continue;
}
if (!file.endsWith('.json')) {
continue;
}
const filePath = fileURLToPath(`${dir}/${file}`);
const reg = /_locales\\(.*?)\\messages\.json/g.exec(filePath);
if (reg) {
const structure = await readFile(filePath, 'utf-8');
const obj = {};
for (const [k, v] of Object.entries(JSON.parse(structure.toString('utf-8'))))
obj[k] = v.message ?? '';
mapper.set(reg[1], obj);
}
}
} catch (ex) {
console.error(ex);
}
return mapper;
}
export { loadLanguages };
export default loadLanguages;