file.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import * as fs from 'node:fs/promises';
  2. import path from 'node:path';
  3. /**
  4. * Load file
  5. * @param path
  6. * @param throwError
  7. * @returns
  8. */
  9. export const loadJSON = async (path, throwError = true) => {
  10. // Get path stat
  11. const stat = await fs.stat(path);
  12. // Return undefined or throw error
  13. if (!stat.isFile()) {
  14. // Handle error
  15. if (throwError) {
  16. throw new Error(`${path} does not exist.`);
  17. }
  18. return;
  19. }
  20. const jsonString = await fs.readFile(path, { encoding: 'utf-8' });
  21. return JSON.parse(jsonString);
  22. };
  23. /**
  24. * Export file
  25. * @param filePath
  26. * @param content
  27. * @returns
  28. */
  29. export const exportFile = async (filePath, content) => {
  30. // Target folder
  31. const folder = path.dirname(filePath);
  32. // Get file stat
  33. const stat = await fs.stat(folder).catch(() => ({
  34. isDirectory: () => false,
  35. }));
  36. // Directory
  37. if (!stat.isDirectory()) {
  38. await fs.mkdir(folder).catch(() => {
  39. return;
  40. });
  41. }
  42. // Write file
  43. return fs.writeFile(filePath, content);
  44. };