ff-admin-server/src/helpers/fileSystemHelper.ts

82 lines
2.5 KiB
TypeScript

import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
import { join } from "path";
import { readdirSync } from "fs";
export abstract class FileSystemHelper {
static createFolder(...args: string[]) {
const exportPath = this.formatPath(...args);
if (!existsSync(exportPath)) {
mkdirSync(exportPath, { recursive: true });
}
}
static readFile(...filePath: string[]) {
this.createFolder(...filePath);
return readFileSync(this.formatPath(...filePath), "utf8");
}
static readFileasBase64(...filePath: string[]) {
this.createFolder(...filePath);
return readFileSync(this.formatPath(...filePath), "base64");
}
static readRootFile(filePath: string) {
return readFileSync(this.normalizePath(process.cwd(), filePath), "utf8");
}
static readTemplateFile(filePath: string) {
return readFileSync(this.normalizePath(process.cwd(), "src", "templates", filePath), "utf8");
}
static readAssetFile(filePath: string, returnPath: boolean = false) {
let path = this.normalizePath(process.cwd(), "src", "assets", filePath);
if (returnPath) {
return path;
}
return readFileSync(path, "utf8");
}
static writeFile(filePath: string, filename: string, file: any) {
this.createFolder(filePath);
let path = this.formatPath(filePath, filename);
writeFileSync(path, file);
}
static deleteFile(...filePath: string[]) {
const path = this.formatPath(...filePath);
if (existsSync(path)) {
unlinkSync(path);
}
}
static formatPath(...args: string[]) {
return join(process.cwd(), "files", ...args);
}
static normalizePath(...args: string[]) {
return join(...args);
}
static getFilesInDirectory(directoryPath: string, filetype?: string): string[] {
const fullPath = this.formatPath(directoryPath);
if (!existsSync(fullPath)) {
return [];
}
return readdirSync(fullPath, { withFileTypes: true })
.filter((dirent) => !dirent.isDirectory() && (!filetype || dirent.name.endsWith(filetype)))
.map((dirent) => dirent.name);
}
static clearDirectoryByFiletype(directoryPath: string, filetype: string) {
const fullPath = this.formatPath(directoryPath);
if (!existsSync(fullPath)) {
return;
}
readdirSync(fullPath, { withFileTypes: true })
.filter((dirent) => !dirent.isDirectory() && dirent.name.endsWith(filetype))
.forEach((dirent) => {
const filePath = join(fullPath, dirent.name);
unlinkSync(filePath);
});
}
}