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

61 lines
1.9 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[]) {
return readFileSync(this.formatPath(...filePath), "utf8");
}
static readFileasBase64(...filePath: string[]) {
return readFileSync(this.formatPath(...filePath), "base64");
}
static readTemplateFile(filePath: string) {
return readFileSync(process.cwd() + filePath, "utf8");
}
static writeFile(filePath: string, filename: string, file: any) {
this.createFolder(filePath);
let path = this.formatPath(filePath, filename);
writeFileSync(path, file);
}
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);
});
}
}