fs.helpers.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import fs from 'fs-extra';
  2. import childProcess from 'child_process';
  3. import { getConfig } from '../../core/config/TipiConfig';
  4. export const readJsonFile = (path: string): any => {
  5. try {
  6. const rawFile = fs.readFileSync(path)?.toString();
  7. if (!rawFile) {
  8. return null;
  9. }
  10. return JSON.parse(rawFile);
  11. } catch (e) {
  12. return null;
  13. }
  14. };
  15. export const readFile = (path: string): string => {
  16. try {
  17. return fs.readFileSync(path).toString();
  18. } catch {
  19. return '';
  20. }
  21. };
  22. export const readdirSync = (path: string): string[] => fs.readdirSync(path);
  23. export const fileExists = (path: string): boolean => fs.existsSync(path);
  24. export const writeFile = (path: string, data: any) => fs.writeFileSync(path, data);
  25. export const createFolder = (path: string) => {
  26. if (!fileExists(path)) {
  27. fs.mkdirSync(path, { recursive: true });
  28. }
  29. };
  30. export const deleteFolder = (path: string) => fs.rmSync(path, { recursive: true });
  31. export const runScript = (path: string, args: string[], callback?: any) => childProcess.execFile(path, args, {}, callback);
  32. export const getSeed = () => {
  33. const seed = readFile('/runtipi/state/seed');
  34. return seed.toString();
  35. };
  36. export const ensureAppFolder = (appName: string, cleanup = false) => {
  37. if (cleanup && fileExists(`/app/storage/apps/${appName}`)) {
  38. deleteFolder(`/app/storage/apps/${appName}`);
  39. }
  40. if (!fileExists(`/app/storage/apps/${appName}/docker-compose.yml`)) {
  41. if (fileExists(`/app/storage/apps/${appName}`)) deleteFolder(`/app/storage/apps/${appName}`);
  42. // Copy from apps repo
  43. fs.copySync(`/runtipi/repos/${getConfig().appsRepoId}/apps/${appName}`, `/app/storage/apps/${appName}`);
  44. }
  45. };