How to create full path with node's fs.mkdirSync?

后端 未结 22 1780
故里飘歌
故里飘歌 2020-11-29 18:03

I\'m trying to create a full path if it doesn\'t exist.

The code looks like this:

var fs = require(\'fs\');
if (!fs.existsSync(newDest)) fs.mkdirSync         


        
相关标签:
22条回答
  • 2020-11-29 18:41

    An asynchronous way to create directories recursively:

    import fs from 'fs'
    
    const mkdirRecursive = function(path, callback) {
      let controlledPaths = []
      let paths = path.split(
        '/' // Put each path in an array
      ).filter(
        p => p != '.' // Skip root path indicator (.)
      ).reduce((memo, item) => {
        // Previous item prepended to each item so we preserve realpaths
        const prevItem = memo.length > 0 ? memo.join('/').replace(/\.\//g, '')+'/' : ''
        controlledPaths.push('./'+prevItem+item)
        return [...memo, './'+prevItem+item]
      }, []).map(dir => {
        fs.mkdir(dir, err => {
          if (err && err.code != 'EEXIST') throw err
          // Delete created directory (or skipped) from controlledPath
          controlledPaths.splice(controlledPaths.indexOf(dir), 1)
          if (controlledPaths.length === 0) {
            return callback()
          }
        })
      })
    }
    
    // Usage
    mkdirRecursive('./photos/recent', () => {
      console.log('Directories created succesfully!')
    })
    
    0 讨论(0)
  • 2020-11-29 18:44

    How about this approach :

    if (!fs.existsSync(pathToFile)) {
                var dirName = "";
                var filePathSplit = pathToFile.split('/');
                for (var index = 0; index < filePathSplit.length; index++) {
                    dirName += filePathSplit[index]+'/';
                    if (!fs.existsSync(dirName))
                        fs.mkdirSync(dirName);
                }
            }
    

    This works for relative path.

    0 讨论(0)
  • 2020-11-29 18:44

    As clean as this :)

    function makedir(fullpath) {
      let destination_split = fullpath.replace('/', '\\').split('\\')
      let path_builder = destination_split[0]
      $.each(destination_split, function (i, path_segment) {
        if (i < 1) return true
        path_builder += '\\' + path_segment
        if (!fs.existsSync(path_builder)) {
          fs.mkdirSync(path_builder)
        }
      })
    }
    
    0 讨论(0)
  • 2020-11-29 18:45

    This version works better on Windows than the top answer because it understands both / and path.sep so that forward slashes work on Windows as they should. Supports absolute and relative paths (relative to the process.cwd).

    /**
     * Creates a folder and if necessary, parent folders also. Returns true
     * if any folders were created. Understands both '/' and path.sep as 
     * path separators. Doesn't try to create folders that already exist,
     * which could cause a permissions error. Gracefully handles the race 
     * condition if two processes are creating a folder. Throws on error.
     * @param targetDir Name of folder to create
     */
    export function mkdirSyncRecursive(targetDir) {
      if (!fs.existsSync(targetDir)) {
        for (var i = targetDir.length-2; i >= 0; i--) {
          if (targetDir.charAt(i) == '/' || targetDir.charAt(i) == path.sep) {
            mkdirSyncRecursive(targetDir.slice(0, i));
            break;
          }
        }
        try {
          fs.mkdirSync(targetDir);
          return true;
        } catch (err) {
          if (err.code !== 'EEXIST') throw err;
        }
      }
      return false;
    }
    
    0 讨论(0)
提交回复
热议问题