我已经阅读了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文档,其中包含错误对象包含什么,参数表示什么等细节。


当前回答

在我看来,在使用Javascript编写代码时,最好不要计算文件系统的命中次数。 然而,(1)stat & mkdir和(2)mkdir和检查(或丢弃)错误代码,这两种方法都是正确的方法来做你想要的。

其他回答

下面是我用来创建目录的ES6代码(当它不存在时):

const fs = require('fs');
const path = require('path');

function createDirectory(directoryPath) {
  const directory = path.normalize(directoryPath);

  return new Promise((resolve, reject) => {
    fs.stat(directory, (error) => {
      if (error) {
        if (error.code === 'ENOENT') {
          fs.mkdir(directory, (error) => {
            if (error) {
              reject(error);
            } else {
              resolve(directory);
            }
          });
        } else {
          reject(error);
        }
      } else {
        resolve(directory);
      }
    });
  });
}

const directoryPath = `${__dirname}/test`;

createDirectory(directoryPath).then((path) => {
  console.log(`Successfully created directory: '${path}'`);
}).catch((error) => {
  console.log(`Problem creating directory: ${error.message}`)
});

注意:

In the beginning of the createDirectory function, I normalize the path to guarantee that the path seperator type of the operating system will be used consistently (e.g. this will turn C:\directory/test into C:\directory\test (when being on Windows) fs.exists is deprecated, that's why I use fs.stat to check if the directory already exists If a directory doesn't exist, the error code will be ENOENT (Error NO ENTry) The directory itself will be created using fs.mkdir I prefer the asynchronous function fs.mkdir over it's blocking counterpart fs.mkdirSync and because of the wrapping Promise it will be guaranteed that the path of the directory will only be returned after the directory has been successfully created

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

$ npm install mkdirp

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

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

    // path exists unless there was an error

});

我提出了一个没有模块的解决方案(对于可维护性,不建议积累模块,特别是对于可以用几行代码编写的小函数……):

最近更新:

在v10.12.0中,NodeJS实现了递归选项:

// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });

更新:

// Get modules node
const fs   = require('fs');
const path = require('path');

// Create 
function mkdirpath(dirPath)
{
    if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
    {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');

Teemu Ikonen的答案非常简单易读,它的一个更新的替代方法是使用fs-extra包的ensureDir方法。

它不仅可以作为内置fs模块的明显替代品,而且除了fs包的功能之外,它还具有许多其他功能。

顾名思义,ensureDir方法确保目录存在。如果目录结构不存在,则创建目录结构。比如mkdir -p。不只是结束文件夹,而是创建整个路径(如果不存在的话)。

上面提供的是它的异步版本。它还有一个同步方法,以ensureDirSync方法的形式执行此操作。

const fs = require('fs');

const folderName = '/Users/joe/test';

try {
  if (!fs.existsSync(folderName)) {
    fs.mkdirSync(folderName);
  }
} catch (err) {
  console.error(err);
}

有关文档和更多示例,请参见https://nodejs.dev/learn/working-with-folders-in-nodejs