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

后端 未结 22 1781
故里飘歌
故里飘歌 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:32

    Exec can be messy on windows. There is a more "nodie" solution. Fundamentally, you have a recursive call to see if a directory exists and dive into the child (if it does exist) or create it. Here is a function that will create the children and call a function when finished:

    fs = require('fs');
    makedirs = function(path, func) {
     var pth = path.replace(/['\\]+/g, '/');
     var els = pth.split('/');
     var all = "";
     (function insertOne() {
       var el = els.splice(0, 1)[0];
       if (!fs.existsSync(all + el)) {
        fs.mkdirSync(all + el);
       }
       all += el + "/";
       if (els.length == 0) {
        func();
       } else {
         insertOne();
       }
       })();
    

    }

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

    A more robust answer is to use use mkdirp.

    var mkdirp = require('mkdirp');
    
    mkdirp('/path/to/dir', function (err) {
        if (err) console.error(err)
        else console.log('dir created')
    });
    

    Then proceed to write the file into the full path with:

    fs.writeFile ('/path/to/dir/file.dat'....
    
    0 讨论(0)
  • 2020-11-29 18:35

    Too many answers, but here's a solution without recursion that works by splitting the path and then left-to-right building it back up again

    function mkdirRecursiveSync(path) {
        let paths = path.split(path.delimiter);
        let fullPath = '';
        paths.forEach((path) => {
    
            if (fullPath === '') {
                fullPath = path;
            } else {
                fullPath = fullPath + '/' + path;
            }
    
            if (!fs.existsSync(fullPath)) {
                fs.mkdirSync(fullPath);
            }
        });
    };
    

    For those concerned about windows vs Linux compatibility, simply replace the forward slash with double backslash '\' in both occurrence above but TBH we are talking about node fs not windows command line and the former is pretty forgiving and the above code will simply work on Windows and is more a complete solution cross platform.

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

    Here's my imperative version of mkdirp for nodejs.

    function mkdirSyncP(location) {
        let normalizedPath = path.normalize(location);
        let parsedPathObj = path.parse(normalizedPath);
        let curDir = parsedPathObj.root;
        let folders = parsedPathObj.dir.split(path.sep);
        folders.push(parsedPathObj.base);
        for(let part of folders) {
            curDir = path.join(curDir, part);
            if (!fs.existsSync(curDir)) {
                fs.mkdirSync(curDir);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-29 18:38

    Using reduce we can verify if each path exists and create it if necessary, also this way I think it is easier to follow. Edited, thanks @Arvin, we should use path.sep to get the proper platform-specific path segment separator.

    const path = require('path');
    
    // Path separators could change depending on the platform
    const pathToCreate = 'path/to/dir'; 
    pathToCreate
     .split(path.sep)
     .reduce((prevPath, folder) => {
       const currentPath = path.join(prevPath, folder, path.sep);
       if (!fs.existsSync(currentPath)){
         fs.mkdirSync(currentPath);
       }
       return currentPath;
     }, '');
    
    0 讨论(0)
  • 2020-11-29 18:40

    One option is to use shelljs module

    npm install shelljs

    var shell = require('shelljs');
    shell.mkdir('-p', fullPath);
    

    From that page:

    Available options:

    p: full path (will create intermediate dirs if necessary)

    As others have noted, there's other more focused modules. But, outside of mkdirp, it has tons of other useful shell operations (like which, grep etc...) and it works on windows and *nix

    0 讨论(0)
提交回复
热议问题