mkdirs.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var fs = require('graceful-fs')
  2. var path = require('path')
  3. var o777 = parseInt('0777', 8)
  4. function mkdirs (p, opts, callback, made) {
  5. if (typeof opts === 'function') {
  6. callback = opts
  7. opts = {}
  8. } else if (!opts || typeof opts !== 'object') {
  9. opts = { mode: opts }
  10. }
  11. var mode = opts.mode
  12. var xfs = opts.fs || fs
  13. if (mode === undefined) {
  14. mode = o777 & (~process.umask())
  15. }
  16. if (!made) made = null
  17. callback = callback || function () {}
  18. p = path.resolve(p)
  19. xfs.mkdir(p, mode, function (er) {
  20. if (!er) {
  21. made = made || p
  22. return callback(null, made)
  23. }
  24. switch (er.code) {
  25. case 'ENOENT':
  26. if (path.dirname(p) === p) return callback(er)
  27. mkdirs(path.dirname(p), opts, function (er, made) {
  28. if (er) callback(er, made)
  29. else mkdirs(p, opts, callback, made)
  30. })
  31. break
  32. // In the case of any other error, just see if there's a dir
  33. // there already. If so, then hooray! If not, then something
  34. // is borked.
  35. default:
  36. xfs.stat(p, function (er2, stat) {
  37. // if the stat fails, then that's super weird.
  38. // let the original error be the failure reason.
  39. if (er2 || !stat.isDirectory()) callback(er, made)
  40. else callback(null, made)
  41. })
  42. break
  43. }
  44. })
  45. }
  46. module.exports = mkdirs