我已经阅读了Node.js的文档,除非我错过了一些东西,否则它不会告诉某些操作中的参数包含什么,特别是fs.mkdir()。正如您在文档中看到的,它不是很多。

目前,我有这段代码,它试图创建一个文件夹或使用一个现有的:

fs.mkdir(path,function(e){
    if(!e || (e && e.code === 'EEXIST')){
        //do something with contents
    } else {
        //debug
        console.log(e);
    }
});

但我想知道这是正确的方法吗?检查代码EEXIST是知道文件夹已经存在的正确方法吗?我知道我可以在创建目录之前执行fs.stat(),但这已经是两次对文件系统的访问了。

其次,是否有一个完整的或至少更详细的Node.js文档,其中包含错误对象包含什么,参数表示什么等细节。


当前回答

实现这一点的好方法是使用mkdirp模块。

$ npm install mkdirp

使用它来运行需要该目录的函数。回调函数在路径创建后或路径已经存在时调用。mkdirp创建目录路径失败,设置错误err。

var mkdirp = require('mkdirp');
mkdirp('/tmp/some/path/foo', function(err) { 

    // path exists unless there was an error

});

其他回答

如果你想要一个快速而脏的眼线笔,使用这个:

fs.existsSync("directory") || fs.mkdirSync("directory");

您可以使用File System模块完成所有这些操作。

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.
})

您甚至不需要检查目录是否存在。下面的代码还保证目录已经存在或已创建。

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.
})

为每个用户创建动态名称目录…使用这段代码

***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");
}

Raugaral的回答,但是有-p功能。很丑,但很管用:

function mkdirp(dir) {
    let dirs = dir.split(/\\/).filter(asdf => !asdf.match(/^\s*$/))
    let fullpath = ''

    // Production directory will begin \\, test is on my local drive.
    if (dirs[0].match(/C:/i)) {
        fullpath = dirs[0] + '\\'
    }
    else {
        fullpath = '\\\\' + dirs[0] + '\\'
    }

    // Start from root directory + 1, build out one level at a time.
    dirs.slice(1).map(asdf => {
        fullpath += asdf + '\\'
        if (!fs.existsSync(fullpath)) {
            fs.mkdirSync(fullpath)
        }
    })
}//mkdirp

编辑:因为这个答案很流行,我更新了它,以反映最新的实践。

节点> = 10

Node的fs的新{recursive: true}选项现在允许本机执行此操作。该选项模仿UNIX的mkdir -p的行为。它将递归地确保路径的每个部分都存在,如果其中任何一部分存在,也不会抛出错误。

(注意:它仍然可能抛出诸如EPERM或EACCESS之类的错误,所以如果你的实现容易受到它的影响,最好还是将它包装在try {} catch (e){}中。)

同步版本。

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

异步版本

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

Node旧版本

使用try {} catch (err){},您可以非常优雅地实现这一点,而不会遇到竞争条件。

为了避免在检查是否存在和创建目录之间出现死时间,我们简单地尝试直接创建它,如果它是EEXIST(目录已经存在),则忽略错误。

但是,如果错误不是EEXIST,我们应该抛出一个错误,因为我们可能在处理EPERM或EACCES之类的错误

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

对于类似mkdir -p的递归行为,例如./a/b/c,你必须在dirpath的每个部分调用它,例如./a, ./a/b, .a/b/c