mkpath.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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, callback);
  20. }
  21. });
  22. } else {
  23. callback(err);
  24. }
  25. } else if (stats.isDirectory()) {
  26. callback(null);
  27. } else {
  28. callback(new Error(dirpath + ' exists and is not a directory'));
  29. }
  30. });
  31. };
  32. mkpath.sync = function mkpathsync(dirpath, mode) {
  33. dirpath = path.resolve(dirpath);
  34. if (typeof mode === 'undefined') {
  35. mode = 0777 & (~process.umask());
  36. }
  37. try {
  38. if (!fs.statSync(dirpath).isDirectory()) {
  39. throw new Error(dirpath + ' exists and is not a directory');
  40. }
  41. } catch (err) {
  42. if (err.code === 'ENOENT') {
  43. mkpathsync(path.dirname(dirpath), mode);
  44. fs.mkdirSync(dirpath, mode);
  45. } else {
  46. throw err;
  47. }
  48. }
  49. };
  50. module.exports = mkpath;