fs-helper.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import * as fs from 'fs'
  2. export function directoryExistsSync(path: string, required?: boolean): boolean {
  3. if (!path) {
  4. throw new Error("Arg 'path' must not be empty")
  5. }
  6. let stats: fs.Stats
  7. try {
  8. stats = fs.statSync(path)
  9. } catch (error) {
  10. if ((error as any)?.code === 'ENOENT') {
  11. if (!required) {
  12. return false
  13. }
  14. throw new Error(`Directory '${path}' does not exist`)
  15. }
  16. throw new Error(
  17. `Encountered an error when checking whether path '${path}' exists: ${(error as any)
  18. ?.message ?? error}`
  19. )
  20. }
  21. if (stats.isDirectory()) {
  22. return true
  23. } else if (!required) {
  24. return false
  25. }
  26. throw new Error(`Directory '${path}' does not exist`)
  27. }
  28. export function existsSync(path: string): boolean {
  29. if (!path) {
  30. throw new Error("Arg 'path' must not be empty")
  31. }
  32. try {
  33. fs.statSync(path)
  34. } catch (error) {
  35. if ((error as any)?.code === 'ENOENT') {
  36. return false
  37. }
  38. throw new Error(
  39. `Encountered an error when checking whether path '${path}' exists: ${(error as any)
  40. ?.message ?? error}`
  41. )
  42. }
  43. return true
  44. }
  45. export function fileExistsSync(path: string): boolean {
  46. if (!path) {
  47. throw new Error("Arg 'path' must not be empty")
  48. }
  49. let stats: fs.Stats
  50. try {
  51. stats = fs.statSync(path)
  52. } catch (error) {
  53. if ((error as any)?.code === 'ENOENT') {
  54. return false
  55. }
  56. throw new Error(
  57. `Encountered an error when checking whether path '${path}' exists: ${(error as any)
  58. ?.message ?? error}`
  59. )
  60. }
  61. if (!stats.isDirectory()) {
  62. return true
  63. }
  64. return false
  65. }