fs-helper.ts 1.5 KB

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