fs.ts 997 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { promises as fs } from 'node:fs';
  2. import { dirname } from 'node:path';
  3. export async function outputJSON(
  4. filePath: string,
  5. data: any,
  6. spaces: number = 2,
  7. ) {
  8. try {
  9. const dir = dirname(filePath);
  10. await fs.mkdir(dir, { recursive: true });
  11. const jsonData = JSON.stringify(data, null, spaces);
  12. await fs.writeFile(filePath, jsonData, 'utf8');
  13. } catch (error) {
  14. console.error('Error writing JSON file:', error);
  15. throw error;
  16. }
  17. }
  18. export async function ensureFile(filePath: string) {
  19. try {
  20. const dir = dirname(filePath);
  21. await fs.mkdir(dir, { recursive: true });
  22. await fs.writeFile(filePath, '', { flag: 'a' });
  23. } catch (error) {
  24. console.error('Error ensuring file:', error);
  25. throw error;
  26. }
  27. }
  28. export async function readJSON(filePath: string) {
  29. try {
  30. const data = await fs.readFile(filePath, 'utf8');
  31. return JSON.parse(data);
  32. } catch (error) {
  33. console.error('Error reading JSON file:', error);
  34. throw error;
  35. }
  36. }