如何使用节点的fs.mkdirSync创建完整路径?

node.js Node.js

Near达蒙

2020-04-03

我正在尝试创建完整路径(如果不存在)。

代码如下:

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

I feel like it should be that simple to recursively create a directory that doesn't exist. Am I missing something or do I need to parse the path and check each directory and create it if it doesn't already exist?

I'm pretty new to Node. Maybe I'm using an old version of FS?

第3894篇《如何使用节点的fs.mkdirSync创建完整路径?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
Itachi 2020.04.03

您可以简单地递归检查路径中是否存在文件夹,并在检查文件夹是否不存在时对其进行设置。没有外部图书馆

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('/')); 
        }
    });
}
小胖Gil 2020.04.03

现在10.12.0使用NodeJS > = ,您可以使用fs.mkdirSync(path, { recursive: true }) fs.mkdirSync

卡卡西 2020.04.03

此功能已在10.12.0版中添加到node.js中,因此就像将选项{recursive: true}作为第二个参数传递给fs.mkdir()调用一样简单。请参阅官方文档中示例

无需外部模块或您自己的实现。

小卤蛋 2020.04.03

fs-extra添加了本机fs模块中未包含的文件系统方法。它代替了fs。

安装 fs-extra

$ npm install --save 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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android