Node.js create folder or use existing

后端 未结 14 1427
暖寄归人
暖寄归人 2020-12-04 06:43

I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdi

相关标签:
14条回答
  • 2020-12-04 07:26

    If you want a quick-and-dirty one liner, use this:

    fs.existsSync("directory") || fs.mkdirSync("directory");
    
    0 讨论(0)
  • 2020-12-04 07:26

    You can use this:

    if(!fs.existsSync("directory")){
        fs.mkdirSync("directory", 0766, function(err){
            if(err){
                console.log(err);
                // echo the result back
                response.send("ERROR! Can't make the directory! \n");
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-04 07:28

    create dynamic name directory for each user... use this code

    ***suppose email contain user mail address***
    
    var filessystem = require('fs');
    var dir = './public/uploads/'+email;
    
    if (!filessystem.existsSync(dir)){
      filessystem.mkdirSync(dir);
    
    }else
    {
        console.log("Directory already exist");
    }
    
    0 讨论(0)
  • 2020-12-04 07:29

    Just as a newer alternative to Teemu Ikonen's answer, which is very simple and easily readable, is to use the ensureDir method of the fs-extra package.

    It can not only be used as a blatant replacement for the built in fs module, but also has a lot of other functionalities in addition to the functionalities of the fs package.

    The ensureDir method, as the name suggests, ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p. Not just the end folder, instead the entire path is created if not existing already.

    the one provided above is the async version of it. It also has a synchronous method to perform this in the form of the ensureDirSync method.

    0 讨论(0)
  • 2020-12-04 07:31

    You can do all of this with the File System module.

    const
      fs = require('fs'),
      dirPath = `path/to/dir`
    
    // Check if directory exists.
    fs.access(dirPath, fs.constants.F_OK, (err)=>{
      if (err){
        // Create directory if directory does not exist.
        fs.mkdir(dirPath, {recursive:true}, (err)=>{
          if (err) console.log(`Error creating directory: ${err}`)
          else console.log('Directory created successfully.')
        })
      }
      // Directory now exists.
    })
    

    You really don't even need to check if the directory exists. The following code also guarantees that the directory either already exists or is created.

    const
      fs = require('fs'),
      dirPath = `path/to/dir`
    
    // Create directory if directory does not exist.
    fs.mkdir(dirPath, {recursive:true}, (err)=>{
      if (err) console.log(`Error creating directory: ${err}`)
      // Directory now exists.
    })
    
    0 讨论(0)
  • 2020-12-04 07:36

    Edit: Because this answer is very popular, I have updated it to reflect up-to-date practices.

    Node >=10

    The new { recursive: true } option of Node's fs now allows this natively. This option mimics the behaviour of UNIX's mkdir -p. It will recursively make sure every part of the path exist, and will not throw an error if any of them do.

    (Note: it might still throw errors such as EPERM or EACCESS, so better still wrap it in a try {} catch (e) {} if your implementation is susceptible to it.)

    Synchronous version.

    fs.mkdirSync(dirpath, { recursive: true })
    

    Async version

    await fs.promises.mkdir(dirpath, { recursive: true })
    

    Older Node versions

    Using a try {} catch (err) {}, you can achieve this very gracefully without encountering a race condition.

    In order to prevent dead time between checking for existence and creating the directory, we simply try to create it straight up, and disregard the error if it is EEXIST (directory already exists).

    If the error is not EEXIST, however, we ought to throw an error, because we could be dealing with something like an EPERM or EACCES

    function ensureDirSync (dirpath) {
      try {
        return fs.mkdirSync(dirpath)
      } catch (err) {
        if (err.code !== 'EEXIST') throw err
      }
    }
    

    For mkdir -p-like recursive behaviour, e.g. ./a/b/c, you'd have to call it on every part of the dirpath, e.g. ./a, ./a/b, .a/b/c

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