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

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

    Based on mouneer's zero-dependencies answer, here's a slightly more beginner friendly Typescript variant, as a module:

    import * as fs from 'fs';
    import * as path from 'path';
    
    /**
    * Recursively creates directories until `targetDir` is valid.
    * @param targetDir target directory path to be created recursively.
    * @param isRelative is the provided `targetDir` a relative path?
    */
    export function mkdirRecursiveSync(targetDir: string, isRelative = false) {
        const sep = path.sep;
        const initDir = path.isAbsolute(targetDir) ? sep : '';
        const baseDir = isRelative ? __dirname : '.';
    
        targetDir.split(sep).reduce((prevDirPath, dirToCreate) => {
            const curDirPathToCreate = path.resolve(baseDir, prevDirPath, dirToCreate);
            try {
                fs.mkdirSync(curDirPathToCreate);
            } catch (err) {
                if (err.code !== 'EEXIST') {
                    throw err;
                }
                // caught EEXIST error if curDirPathToCreate already existed (not a problem for us).
            }
    
            return curDirPathToCreate; // becomes prevDirPath on next call to reduce
        }, initDir);
    }
    
    0 讨论(0)
  • 2020-11-29 18:20

    I solved the problem this way - similar to other recursive answers but to me this is much easier to understand and read.

    const path = require('path');
    const fs = require('fs');
    
    function mkdirRecurse(inputPath) {
      if (fs.existsSync(inputPath)) {
        return;
      }
      const basePath = path.dirname(inputPath);
      if (fs.existsSync(basePath)) {
        fs.mkdirSync(inputPath);
      }
      mkdirRecurse(basePath);
    }
    
    0 讨论(0)
  • 2020-11-29 18:21

    You can simply check folder exist or not in path recursively and make the folder as you check if they are not present. (NO EXTERNAL LIBRARY)

    function checkAndCreateDestinationPath (fileDestination) {
        const dirPath = fileDestination.split('/');
        dirPath.forEach((element, index) => {
            if(!fs.existsSync(dirPath.slice(0, index + 1).join('/'))){
                fs.mkdirSync(dirPath.slice(0, index + 1).join('/')); 
            }
        });
    }
    
    0 讨论(0)
  • 2020-11-29 18:23

    You can use the next function

    const recursiveUpload = (path: string) => { const paths = path.split("/")

    const fullPath = paths.reduce((accumulator, current) => {
      fs.mkdirSync(accumulator)
      return `${accumulator}/${current}`
      })
    
      fs.mkdirSync(fullPath)
    
      return fullPath
    }
    

    So what it does:

    1. Create paths variable, where it stores every path by itself as an element of the array.
    2. Adds "/" at the end of each element in the array.
    3. Makes for the cycle:
      1. Creates a directory from the concatenation of array elements which indexes are from 0 to current iteration. Basically, it is recursive.

    Hope that helps!

    By the way, in Node v10.12.0 you can use recursive path creation by giving it as the additional argument.

    fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; });

    https://nodejs.org/api/fs.html#fs_fs_mkdirsync_path_options

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

    This feature has been added to node.js in version 10.12.0, so it's as easy as passing an option {recursive: true} as second argument to the fs.mkdir() call. See the example in the official docs.

    No need for external modules or your own implementation.

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

    i know this is an old question, but nodejs v10.12.0 now supports this natively with the recursive option set to true. fs.mkdir

    // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
    fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
      if (err) throw err;
    });
    
    0 讨论(0)
提交回复
热议问题