fs.helpers.ts 1.8 KB

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