mkdirs.js 1.6 KB

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