mkdir.js 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. import { mkdirSync } from 'fs'
  2. import { sep, isAbsolute, resolve } from 'path'
  3. export function mkDirByPathSync (targetDir, { isRelativeToScript = false } = {}) {
  4. const seperator = sep
  5. const initDir = isAbsolute(targetDir) ? seperator : ''
  6. const baseDir = isRelativeToScript ? __dirname : '.'
  7. return targetDir.split(seperator).reduce((parentDir, childDir) => {
  8. const curDir = resolve(baseDir, parentDir, childDir)
  9. try {
  10. mkdirSync(curDir)
  11. } catch (err) {
  12. if (err.code === 'EEXIST') { // curDir already exists!
  13. return curDir
  14. }
  15. // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
  16. if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
  17. throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`)
  18. }
  19. const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1
  20. if (!caughtErr || (caughtErr && curDir) === resolve(targetDir)) {
  21. throw err // Throw if it's just the last created dir.
  22. }
  23. }
  24. return curDir
  25. }, initDir)
  26. }