file-utils.mjs 739 B

123456789101112131415161718192021222324252627
  1. import * as fs from "fs/promises"
  2. import * as path from "path"
  3. /**
  4. * Write `contents` to `filePath`, creating any necessary directories in `filePath`.
  5. */
  6. export async function writeFileWithMkdirs(filePath, content) {
  7. await fs.mkdir(path.dirname(filePath), { recursive: true })
  8. await fs.writeFile(filePath, content)
  9. }
  10. export async function rmrf(path) {
  11. await fs.rm(path, { force: true, recursive: true })
  12. }
  13. /**
  14. * Remove an empty dir, do nothing if the directory doesn't exist or is not empty.
  15. */
  16. export async function rmdir(path) {
  17. try {
  18. await fs.rmdir(path)
  19. } catch (error) {
  20. if (error.code !== "ENOTEMPTY" && error.code !== "ENOENT") {
  21. // Only re-throw if it's not "not empty" or "doesn't exist"
  22. throw error
  23. }
  24. }
  25. }