mkdirp-manual.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const {dirname} = require('path')
  2. const mkdirpManual = (path, opts, made) => {
  3. opts.recursive = false
  4. const parent = dirname(path)
  5. if (parent === path) {
  6. return opts.mkdirAsync(path, opts).catch(er => {
  7. // swallowed by recursive implementation on posix systems
  8. // any other error is a failure
  9. if (er.code !== 'EISDIR')
  10. throw er
  11. })
  12. }
  13. return opts.mkdirAsync(path, opts).then(() => made || path, er => {
  14. if (er.code === 'ENOENT')
  15. return mkdirpManual(parent, opts)
  16. .then(made => mkdirpManual(path, opts, made))
  17. if (er.code !== 'EEXIST' && er.code !== 'EROFS')
  18. throw er
  19. return opts.statAsync(path).then(st => {
  20. if (st.isDirectory())
  21. return made
  22. else
  23. throw er
  24. }, () => { throw er })
  25. })
  26. }
  27. const mkdirpManualSync = (path, opts, made) => {
  28. const parent = dirname(path)
  29. opts.recursive = false
  30. if (parent === path) {
  31. try {
  32. return opts.mkdirSync(path, opts)
  33. } catch (er) {
  34. // swallowed by recursive implementation on posix systems
  35. // any other error is a failure
  36. if (er.code !== 'EISDIR')
  37. throw er
  38. else
  39. return
  40. }
  41. }
  42. try {
  43. opts.mkdirSync(path, opts)
  44. return made || path
  45. } catch (er) {
  46. if (er.code === 'ENOENT')
  47. return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))
  48. if (er.code !== 'EEXIST' && er.code !== 'EROFS')
  49. throw er
  50. try {
  51. if (!opts.statSync(path).isDirectory())
  52. throw er
  53. } catch (_) {
  54. throw er
  55. }
  56. }
  57. }
  58. module.exports = {mkdirpManual, mkdirpManualSync}