我试图创建一个完整的路径,如果它不存在。

代码如下所示:

var fs = require('fs');
if (!fs.existsSync(newDest)) fs.mkdirSync(newDest); 

只要只有一个子目录(像'dir1'这样的newDest),这段代码就能很好地工作,但是当有一个目录路径('dir1/dir2')时,它就会失败 错误:ENOENT,没有这样的文件或目录

我希望能够用尽可能少的代码行创建完整的路径。

我读到fs上有一个递归选项,并尝试了这样做

var fs = require('fs');
if (!fs.existsSync(newDest)) fs.mkdirSync(newDest,'0777', true);

我觉得递归地创建一个不存在的目录应该这么简单。我是否遗漏了一些东西,或者我是否需要解析路径并检查每个目录,如果它不存在,则创建它?

我对Node很陌生。也许我使用的是旧版本的FS?


当前回答

我用这种方法解决了这个问题——类似于其他递归的答案,但对我来说,这更容易理解和阅读。

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

其他回答

fs-extra添加了本地fs模块中不包含的文件系统方法。它是fs替换量的下降。

安装fs-extra

$ NPM install——保存fs-extra

const fs = require("fs-extra");
// Make sure the output directory is there.
fs.ensureDirSync(newDest);

有同步和异步选项。

https://github.com/jprichardson/node-fs-extra/blob/master/docs/ensureDir.md

Windows的示例(没有额外的依赖和错误处理)

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

let dir = "C:\\temp\\dir1\\dir2\\dir3";

function createDirRecursively(dir) {
    if (!fs.existsSync(dir)) {        
        createDirRecursively(path.join(dir, ".."));
        fs.mkdirSync(dir);
    }
}

createDirRecursively(dir); //creates dir1\dir2\dir3 in C:\temp

更新

NodeJS 10.12.0版本增加了对mkdir和mkdirSync的本地支持,使用recursive: true选项递归地创建目录,如下所示:

fs.mkdirSync(targetDir, { recursive: true });

如果你喜欢fs Promises API,你可以写

fs.promises.mkdir(targetDir, { recursive: true });

原来的答案

如果目录不存在,则递归地创建目录!(零依赖关系)

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

function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
  const sep = path.sep;
  const initDir = path.isAbsolute(targetDir) ? sep : '';
  const baseDir = isRelativeToScript ? __dirname : '.';

  return targetDir.split(sep).reduce((parentDir, childDir) => {
    const curDir = path.resolve(baseDir, parentDir, childDir);
    try {
      fs.mkdirSync(curDir);
    } catch (err) {
      if (err.code === 'EEXIST') { // curDir already exists!
        return curDir;
      }

      // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
      if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
        throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
      }

      const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
      if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
        throw err; // Throw if it's just the last created dir.
      }
    }

    return curDir;
  }, initDir);
}

使用

// Default, make directories relative to current working directory.
mkDirByPathSync('path/to/dir');

// Make directories relative to the current script.
mkDirByPathSync('path/to/dir', {isRelativeToScript: true});

// Make directories with an absolute path.
mkDirByPathSync('/path/to/dir');

Demo

试一试!

解释

[UPDATE] This solution handles platform-specific errors like EISDIR for Mac and EPERM and EACCES for Windows. Thanks to all the reporting comments by @PediT., @JohnQ, @deed02392, @robyoder and @Almenon. This solution handles both relative and absolute paths. Thanks to @john comment. In the case of relative paths, target directories will be created (resolved) in the current working directory. To Resolve them relative to the current script dir, pass {isRelativeToScript: true}. Using path.sep and path.resolve(), not just / concatenation, to avoid cross-platform issues. Using fs.mkdirSync and handling the error with try/catch if thrown to handle race conditions: another process may add the file between the calls to fs.existsSync() and fs.mkdirSync() and causes an exception. The other way to achieve that could be checking if a file exists then creating it, I.e, if (!fs.existsSync(curDir) fs.mkdirSync(curDir);. But this is an anti-pattern that leaves the code vulnerable to race conditions. Thanks to @GershomMaes comment about the directory existence check. Requires Node v6 and newer to support destructuring. (If you have problems implementing this solution with old Node versions, just leave me a comment)

您可以使用下一个函数

const recursiveUpload =(路径:字符串)=> { Const paths = path.split("/")

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

  fs.mkdirSync(fullPath)

  return fullPath
}

它的作用是:

创建路径变量,它将每个路径单独存储为数组的一个元素。 在数组中每个元素的末尾添加"/"。 形成循环: 从索引从0到当前迭代的数组元素的连接中创建一个目录。基本上,它是递归的。

希望有帮助!

顺便说一下,在Node v10.12.0中,可以通过将递归路径创建作为附加参数来使用。

fs。mkdir(“/ tmp / /苹果”,{递归:真},(err) = > { 如果(错误)抛出错误; });

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

像这样干净:)

function makedir(fullpath) {
  let destination_split = fullpath.replace('/', '\\').split('\\')
  let path_builder = destination_split[0]
  $.each(destination_split, function (i, path_segment) {
    if (i < 1) return true
    path_builder += '\\' + path_segment
    if (!fs.existsSync(path_builder)) {
      fs.mkdirSync(path_builder)
    }
  })
}