index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. var path = require('path');
  2. var fs = require('fs');
  3. var _0777 = parseInt('0777', 8);
  4. module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
  5. function mkdirP (p, opts, f, made) {
  6. if (typeof opts === 'function') {
  7. f = opts;
  8. opts = {};
  9. }
  10. else if (!opts || typeof opts !== 'object') {
  11. opts = { mode: opts };
  12. }
  13. var mode = opts.mode;
  14. var xfs = opts.fs || fs;
  15. if (mode === undefined) {
  16. mode = _0777
  17. }
  18. if (!made) made = null;
  19. var cb = f || function () {};
  20. p = path.resolve(p);
  21. xfs.mkdir(p, mode, function (er) {
  22. if (!er) {
  23. made = made || p;
  24. return cb(null, made);
  25. }
  26. switch (er.code) {
  27. case 'ENOENT':
  28. if (path.dirname(p) === p) return cb(er);
  29. mkdirP(path.dirname(p), opts, function (er, made) {
  30. if (er) cb(er, made);
  31. else mkdirP(p, opts, cb, made);
  32. });
  33. break;
  34. // In the case of any other error, just see if there's a dir
  35. // there already. If so, then hooray! If not, then something
  36. // is borked.
  37. default:
  38. xfs.stat(p, function (er2, stat) {
  39. // if the stat fails, then that's super weird.
  40. // let the original error be the failure reason.
  41. if (er2 || !stat.isDirectory()) cb(er, made)
  42. else cb(null, made);
  43. });
  44. break;
  45. }
  46. });
  47. }
  48. mkdirP.sync = function sync (p, opts, made) {
  49. if (!opts || typeof opts !== 'object') {
  50. opts = { mode: opts };
  51. }
  52. var mode = opts.mode;
  53. var xfs = opts.fs || fs;
  54. if (mode === undefined) {
  55. mode = _0777
  56. }
  57. if (!made) made = null;
  58. p = path.resolve(p);
  59. try {
  60. xfs.mkdirSync(p, mode);
  61. made = made || p;
  62. }
  63. catch (err0) {
  64. switch (err0.code) {
  65. case 'ENOENT' :
  66. made = sync(path.dirname(p), opts, made);
  67. sync(p, opts, made);
  68. break;
  69. // In the case of any other error, just see if there's a dir
  70. // there already. If so, then hooray! If not, then something
  71. // is borked.
  72. default:
  73. var stat;
  74. try {
  75. stat = xfs.statSync(p);
  76. }
  77. catch (err1) {
  78. throw err0;
  79. }
  80. if (!stat.isDirectory()) throw err0;
  81. break;
  82. }
  83. }
  84. return made;
  85. };