summary refs log tree commit diff
path: root/src/util/FileStorage.ts
blob: b87c46518d06f7844814cdd10106988f2380b6b4 (plain) (blame)
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
import { Storage } from "./Storage";
import fs from "fs";
import { join } from "path";
import "missing-native-js-functions";

export class FileStorage implements Storage {
	async get(path: string): Promise<Buffer | null> {
		path = join(process.env.STORAGE_LOCATION || "", path);
		try {
			const file = fs.readFileSync(path);
			// @ts-ignore
			return file;
		} catch (error) {
			return null;
		}
	}

	async set(path: string, value: any) {
		path = join(process.env.STORAGE_LOCATION || "", path).replace(/[\\]/g, "/");
		const dir = path.split("/").slice(0, -1).join("/");
		fs.mkdirSync(dir, { recursive: true });

		return fs.writeFileSync(path, value, { encoding: "binary" });
	}

	async delete(path: string) {
		path = join(process.env.STORAGE_LOCATION || "", path);
		fs.unlinkSync(path);
	}
}