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

代码如下所示:

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

其他回答

使用reduce,我们可以验证每个路径是否存在,并在必要时创建它,而且我认为这样更容易遵循。编辑,谢谢@Arvin,我们应该使用路径。Sep来获得适当的平台特定路径段分隔符。

const path = require('path');

// Path separators could change depending on the platform
const pathToCreate = 'path/to/dir'; 
pathToCreate
 .split(path.sep)
 .reduce((prevPath, folder) => {
   const currentPath = path.join(prevPath, folder, path.sep);
   if (!fs.existsSync(currentPath)){
     fs.mkdirSync(currentPath);
   }
   return currentPath;
 }, '');

这个版本在Windows上比上面的答案工作得更好,因为它同时理解/和路径。sep,以便向前斜杠在Windows上工作,因为他们应该。支持绝对路径和相对路径(相对于process.cwd)。

/**
 * Creates a folder and if necessary, parent folders also. Returns true
 * if any folders were created. Understands both '/' and path.sep as 
 * path separators. Doesn't try to create folders that already exist,
 * which could cause a permissions error. Gracefully handles the race 
 * condition if two processes are creating a folder. Throws on error.
 * @param targetDir Name of folder to create
 */
export function mkdirSyncRecursive(targetDir) {
  if (!fs.existsSync(targetDir)) {
    for (var i = targetDir.length-2; i >= 0; i--) {
      if (targetDir.charAt(i) == '/' || targetDir.charAt(i) == path.sep) {
        mkdirSyncRecursive(targetDir.slice(0, i));
        break;
      }
    }
    try {
      fs.mkdirSync(targetDir);
      return true;
    } catch (err) {
      if (err.code !== 'EEXIST') throw err;
    }
  }
  return false;
}

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

找不到创建具有所需权限的目录的示例。

使用您想要的权限以异步递归方式创建目录。

下面是一个简单的nodejs解决方案

节点v18.12.1 Ubuntu 18

//-----------------------------
const fs = require('fs');
const fsPromises = fs.promises;
const checkDirAccess = async (userDir) => {
    try {
      await fsPromises.access(userDir, fs.constants.R_OK | fs.constants.W_OK);
      console.log(` ${userDir} Dir existss`);
      return userDir;
    } catch (err) {
        if(err.errno = -2)
            return await crDir(userDir);
        else
            throw err;
    }
}
const crDir = async (userDir) => {
    try {
      let newDir = await fsPromises.mkdir(userDir, { recursive: true, mode: 0o700}); 
      // When userDir is created; newDir = undefined;
      console.log(` Created new Dir ${newDir}`);
      return newDir;
    } catch (err) {
      throw err;
    }
}
const directoryPath =  ['uploads/xvc/xvc/xvc/specs', 'uploads/testDir11', 'uploads/xsXa/', 'uploads//xsb//', 'uploads//xsV/'];

const findDir = async() => {
try {
    for (const iterator of directoryPath) {
        let dirOK = await checkDirAccess(iterator);
        if(dirOK)
           console.log(`found ${dirOK}`)        
    }
    
} catch (error) {
    console.error('Error : ', error);
}
}

答案太多了,但这里有一个没有递归的解决方案,它通过分割路径,然后从左到右重新构建

function mkdirRecursiveSync(path) {
    let paths = path.split(path.delimiter);
    let fullPath = '';
    paths.forEach((path) => {

        if (fullPath === '') {
            fullPath = path;
        } else {
            fullPath = fullPath + '/' + path;
        }

        if (!fs.existsSync(fullPath)) {
            fs.mkdirSync(fullPath);
        }
    });
};

对于那些关心windows与Linux兼容性的人,只需将上面出现的正斜杠替换为双反斜杠'\',但TBH,我们谈论的是节点fs而不是windows命令行,前者是相当宽容的,上面的代码将简单地工作在windows上,是一个更完整的跨平台解决方案。