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

代码如下所示:

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?


当前回答

一个更健壮的答案是使用use mkdirp。

var mkdirp = require('mkdirp');

mkdirp('/path/to/dir', function (err) {
    if (err) console.error(err)
    else console.log('dir created')
});

然后继续将文件写入完整路径:

fs.writeFile ('/path/to/dir/file.dat'....

其他回答

使用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;
 }, '');
const fs = require('fs');

try {
    fs.mkdirSync(path, { recursive: true });
} catch (error) {
    // this make script keep running, even when folder already exist
    console.log(error);
}

你可以简单地检查文件夹存在或不递归的路径,并使文件夹,因为你检查,如果他们不存在。(没有外部库)

function checkAndCreateDestinationPath (fileDestination) {
    const dirPath = fileDestination.split('/');
    dirPath.forEach((element, index) => {
        if(!fs.existsSync(dirPath.slice(0, index + 1).join('/'))){
            fs.mkdirSync(dirPath.slice(0, index + 1).join('/')); 
        }
    });
}

该特性已在10.12.0版本中添加到node.js中,因此只需将选项{recursive: true}作为第二个参数传递给fs.mkdir()调用即可。 请参阅官方文档中的示例。

不需要外部模块或自己的实现。

一种选择是使用shelljs模块

npm install shelljs

var shell = require('shelljs');
shell.mkdir('-p', fullPath);

从那一页开始:

可用的选项: P:全路径(如有必要将创建中间dirs)

正如其他人所注意到的,还有其他更专注的模块。但是,除了mkdirp之外,它还有大量其他有用的shell操作(比如which, grep等等…),并且它可以在windows和*nix上工作

编辑:评论建议这在没有mkdir cli实例的系统上不起作用。事实并非如此。这就是shelljs的重点——创建一个可移植的跨平台shell类函数集。它适用于偶数窗户。