mkdirs-sync.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 mkdirsSync (p, opts, made) {
  6. if (!opts || typeof opts !== 'object') {
  7. opts = { mode: opts }
  8. }
  9. var mode = opts.mode
  10. var xfs = opts.fs || fs
  11. if (process.platform === 'win32' && invalidWin32Path(p)) {
  12. var errInval = new Error(p + ' contains invalid WIN32 path characters.')
  13. errInval.code = 'EINVAL'
  14. throw errInval
  15. }
  16. if (mode === undefined) {
  17. mode = o777 & (~process.umask())
  18. }
  19. if (!made) made = null
  20. p = path.resolve(p)
  21. try {
  22. xfs.mkdirSync(p, mode)
  23. made = made || p
  24. } catch (err0) {
  25. switch (err0.code) {
  26. case 'ENOENT':
  27. if (path.dirname(p) === p) throw err0
  28. made = mkdirsSync(path.dirname(p), opts, made)
  29. mkdirsSync(p, opts, made)
  30. break
  31. // In the case of any other error, just see if there's a dir
  32. // there already. If so, then hooray! If not, then something
  33. // is borked.
  34. default:
  35. var stat
  36. try {
  37. stat = xfs.statSync(p)
  38. } catch (err1) {
  39. throw err0
  40. }
  41. if (!stat.isDirectory()) throw err0
  42. break
  43. }
  44. }
  45. return made
  46. }
  47. module.exports = mkdirsSync