-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.js
More file actions
66 lines (59 loc) · 1.49 KB
/
utils.js
File metadata and controls
66 lines (59 loc) · 1.49 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
55
56
57
58
59
60
61
62
63
64
65
66
import fs from 'node:fs/promises';
import nodePath from 'node:path';
export function assign(obj = {}, lang = '', key = '', value = '') {
// Only add key if value exists
if (!value) return;
obj[lang] ??= {}; // Does lang exist?
obj[lang][key] = value;
}
export async function readJSON(file) {
const content = await fs.readFile(file);
return JSON.parse(content);
}
export async function fileExists(path) {
try {
await fs.access(path);
return true;
} catch {
return false;
}
}
export async function writeFile(path, data) {
const dir = nodePath.dirname(path);
await fs.mkdir(dir, { recursive: true });
return fs.writeFile(path, data);
}
export function sortKeys(obj = {}) {
const keys = Object.keys(obj);
if (!keys.length) return undefined;
const sorted = {};
keys.sort(
(a, b) => uncomment(a).localeCompare(uncomment(b)),
).forEach(
(key) => {
const value = obj[key];
if (Array.isArray(value)) {
sorted[key] = value;
// value.forEach((val, index) => {
// sorted[`${key}.${index + 1}`] = val;
// });
return;
}
sorted[key] = typeof value === 'object' ? sortKeys(value) : value;
},
);
return sorted;
}
/**
* Checks if module is the main module
* @param {ImportMeta} meta
*/
export function isMain({ url }) {
return nodePath.normalize(url).endsWith(process.argv[1]);
}
function uncomment(string = '') {
if (string.startsWith('//')) {
return string.substring(2);
}
return string;
}