-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (56 loc) · 2.07 KB
/
index.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
import fsp from "node:fs/promises";
import path from "node:path";
import console from "node:console";
import fse from "fs-extra";
import JSON5 from "json5";
import sharp from "sharp";
import { v4 } from "uuid";
export async function createJsonStructure(basePath) {
const topLevelStructure = {};
console.log({ basePath });
async function constructStructure(currentPath, object) {
const items = await fsp.readdir(currentPath);
for (const item of items) {
const fullPath = path.join(currentPath, item);
const stats = await fse.stat(fullPath);
if (stats.isDirectory()) {
const itemKey = item;
object[item] = {};
await constructStructure(fullPath, object[itemKey]);
} else if (stats.isFile()) {
const fileExtension = path.extname(fullPath).toLowerCase();
if ([".json", ".json5"].includes(fileExtension)) {
const fileContents = await fsp.readFile(fullPath, "utf8");
const parsedJson = JSON5.parse(fileContents);
object.payload ??= {};
for (const key in parsedJson) {
object.payload[key] = parsedJson[key];
}
object.id = v4();
} else if ([".jpg", ".jpeg", ".png"].includes(fileExtension)) {
const imageBuffer = await fsp.readFile(fullPath);
const resizedImageBuffer = await sharp(imageBuffer)
.resize(256, 256)
.webp({ quality: 60, progressive: true })
.toBuffer();
const base64Image = resizedImageBuffer.toString("base64");
object.payload ??= {};
object.payload.images ??= {};
object.payload.images.thumbnail = `data:image/webp;base64,${base64Image}`;
}
}
}
}
const topLevelDirectories = await fse.readdir(basePath);
for (const directory of topLevelDirectories) {
const fullPath = path.join(basePath, directory);
const stat = await fse.stat(fullPath);
if (stat.isDirectory()) {
topLevelStructure[directory] = {};
await constructStructure(fullPath, topLevelStructure[directory]);
}
}
return topLevelStructure;
}
const json = await createJsonStructure(path.join(process.cwd(), "files"));
await fsp.writeFile("output/captain.json", JSON.stringify(json, null, 2));