mkpath.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var fs = require('fs');
  2. var path = require('path');
  3. var mkpath = function mkpath(dirpath, mode, callback) {
  4. dirpath = path.resolve(dirpath);
  5. if (typeof mode === 'function' || typeof mode === 'undefined') {
  6. callback = mode;
  7. mode = 0777 & (~process.umask());
  8. }
  9. if (!callback) {
  10. callback = function () {};
  11. }
  12. fs.stat(dirpath, function (err, stats) {
  13. if (err) {
  14. if (err.code === 'ENOENT') {
  15. mkpath(path.dirname(dirpath), mode, function (err) {
  16. if (err) {
  17. callback(err);
  18. } else {
  19. fs.mkdir(dirpath, mode, function (err) {
  20. if (!err || err.code == 'EEXIST') {
  21. callback(null);
  22. } else {
  23. callback(err);
  24. }
  25. });
  26. }
  27. });
  28. } else {
  29. callback(err);
  30. }
  31. } else if (stats.isDirectory()) {
  32. callback(null);
  33. } else {
  34. callback(new Error(dirpath + ' exists and is not a directory'));
  35. }
  36. });
  37. };
  38. mkpath.sync = function mkpathsync(dirpath, mode) {
  39. dirpath = path.resolve(dirpath);
  40. if (typeof mode === 'undefined') {
  41. mode = 0777 & (~process.umask());
  42. }
  43. try {
  44. if (!fs.statSync(dirpath).isDirectory()) {
  45. throw new Error(dirpath + ' exists and is not a directory');
  46. }
  47. } catch (err) {
  48. if (err.code === 'ENOENT') {
  49. mkpathsync(path.dirname(dirpath), mode);
  50. fs.mkdirSync(dirpath, mode);
  51. } else {
  52. throw err;
  53. }
  54. }
  55. };
  56. module.exports = mkpath;