fs-helper.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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: ${
  18. (error as any)?.message ?? error
  19. }`
  20. )
  21. }
  22. if (stats.isDirectory()) {
  23. return true
  24. } else if (!required) {
  25. return false
  26. }
  27. throw new Error(`Directory '${path}' does not exist`)
  28. }
  29. export function existsSync(path: string): boolean {
  30. if (!path) {
  31. throw new Error("Arg 'path' must not be empty")
  32. }
  33. try {
  34. fs.statSync(path)
  35. } catch (error) {
  36. if ((error as any)?.code === 'ENOENT') {
  37. return false
  38. }
  39. throw new Error(
  40. `Encountered an error when checking whether path '${path}' exists: ${
  41. (error as any)?.message ?? error
  42. }`
  43. )
  44. }
  45. return true
  46. }
  47. export function fileExistsSync(path: string): boolean {
  48. if (!path) {
  49. throw new Error("Arg 'path' must not be empty")
  50. }
  51. let stats: fs.Stats
  52. try {
  53. stats = fs.statSync(path)
  54. } catch (error) {
  55. if ((error as any)?.code === 'ENOENT') {
  56. return false
  57. }
  58. throw new Error(
  59. `Encountered an error when checking whether path '${path}' exists: ${
  60. (error as any)?.message ?? error
  61. }`
  62. )
  63. }
  64. if (!stats.isDirectory()) {
  65. return true
  66. }
  67. return false
  68. }