如果目录不存在,下面的方法是否正确?

它应该对脚本具有完全的权限,并且其他人可以阅读。

var dir = __dirname + '/upload';
if (!path.existsSync(dir)) {
    fs.mkdirSync(dir, 0744);
}

当前回答

var dir = 'path/to/dir';
try {
  fs.mkdirSync(dir);
} catch(e) {
  if (e.code != 'EEXIST') throw e;
}

其他回答

使用fs-extra包,你可以用一行代码做到这一点:

const fs = require('fs-extra');

const dir = '/tmp/this/path/does/not/exist';
fs.ensureDirSync(dir);

适用于v10及以上节点

正如一些回答指出的那样,从节点10开始,您可以对mkdir使用recursive:true

还没有指出的是,当使用recursive:true时,如果目录已经存在,mkdir不会返回错误。

所以你可以这样做:

fsNative.mkdir(dirPath,{recursive:true},(err) => {
    if(err) {
        //note: this does NOT get triggered if the directory already existed
        console.warn(err)
    }
    else{
        //directory now exists 
    }
})

使用承诺

此外,从节点10开始,您可以通过从fs/promises中要求获得所有fs函数的Promise版本

所以把这两件事放在一起,你就得到了这个简单的解决方案:

import * as fs from 'fs/promises';

await fs.mkdir(dirPath, {recursive:true}).catch((err) => {
    //decide what you want to do if this failed
    console.error(err);
});

//directory now exists

使用Node.js 10 + ES6:

import path from 'path';
import fs from 'fs';

(async () => {
  const dir = path.join(__dirname, 'upload');

  try {
    await fs.promises.mkdir(dir);
  } catch (error) {
    if (error.code === 'EEXIST') {
      // Something already exists, but is it a file or directory?
      const lstat = await fs.promises.lstat(dir);

      if (!lstat.isDirectory()) {
        throw error;
      }
    } else {
      throw error;
    }
  }
})();

mkdir方法能够递归地在一个路径中创建任何不存在的目录,并忽略存在的目录。

来自Node.js v10/11文档:

// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
    if (err) throw err;
});

注意:首先需要导入内置的fs模块。

现在,这里有一个更健壮的例子,它利用了原生ECMAScript模块(启用了标志和.mjs扩展名),处理非根路径,并说明完整的路径名:

import fs from 'fs';
import path from 'path';

function createDirectories(pathname) {
   const __dirname = path.resolve();
   pathname = pathname.replace(/^\.*\/|\/?[^\/]+\.[a-z]+|\/$/g, ''); // Remove leading directory markers, and remove ending /file-name.extension
   fs.mkdir(path.resolve(__dirname, pathname), { recursive: true }, e => {
       if (e) {
           console.error(e);
       } else {
           console.log('Success');
       }
    });
}

你可以像createDirectories('/components/widget/widget.js');一样使用它。

当然,当目录创建时,你可能想要在async/await中使用promises以一种更可读的同步方式来利用文件创建;但是,这超出了问题的范围。

var dir = 'path/to/dir';
try {
  fs.mkdirSync(dir);
} catch(e) {
  if (e.code != 'EEXIST') throw e;
}