You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
983 B

4 years ago
  1. 'use strict'
  2. const u = require('universalify').fromCallback
  3. const fs = require('fs')
  4. const path = require('path')
  5. const mkdir = require('../mkdirs')
  6. const remove = require('../remove')
  7. const emptyDir = u(function emptyDir (dir, callback) {
  8. callback = callback || function () {}
  9. fs.readdir(dir, (err, items) => {
  10. if (err) return mkdir.mkdirs(dir, callback)
  11. items = items.map(item => path.join(dir, item))
  12. deleteItem()
  13. function deleteItem () {
  14. const item = items.pop()
  15. if (!item) return callback()
  16. remove.remove(item, err => {
  17. if (err) return callback(err)
  18. deleteItem()
  19. })
  20. }
  21. })
  22. })
  23. function emptyDirSync (dir) {
  24. let items
  25. try {
  26. items = fs.readdirSync(dir)
  27. } catch (err) {
  28. return mkdir.mkdirsSync(dir)
  29. }
  30. items.forEach(item => {
  31. item = path.join(dir, item)
  32. remove.removeSync(item)
  33. })
  34. }
  35. module.exports = {
  36. emptyDirSync,
  37. emptydirSync: emptyDirSync,
  38. emptyDir,
  39. emptydir: emptyDir
  40. }