index.js 2.5 KB

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