mkdir.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const isFn = require('./isFn');
  2. const noop = require('./noop');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const _0777 = parseInt('0777', 8);
  6. exports = function(p, mode, cb) {
  7. if (isFn(mode)) {
  8. cb = mode;
  9. mode = _0777;
  10. }
  11. cb = cb || noop;
  12. p = path.resolve(p);
  13. fs.mkdir(p, mode, function(err) {
  14. if (!err) return cb();
  15. if (err.code === 'ENOENT') {
  16. exports(path.dirname(p), mode, function(err) {
  17. if (err) return cb(err);
  18. exports(p, mode, cb);
  19. });
  20. } else {
  21. fs.stat(p, function(errStat, stat) {
  22. if (errStat || !stat.isDirectory()) return cb(errStat);
  23. cb();
  24. });
  25. }
  26. });
  27. };
  28. exports.sync = function(p, mode = _0777) {
  29. p = path.resolve(p);
  30. try {
  31. fs.mkdirSync(p, mode);
  32. } catch (err) {
  33. if (err.code === 'ENOENT') {
  34. exports.sync(path.dirname(p), mode);
  35. exports.sync(p, mode);
  36. } else {
  37. try {
  38. if (!fs.statSync(p).isDirectory()) {
  39. throw err;
  40. }
  41. } catch (_) {
  42. throw err;
  43. }
  44. }
  45. }
  46. };
  47. module.exports = exports;