index.js 2.3 KB

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