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.

63 lines
1.6 KiB

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