如何使用节点的fs.mkdirSync创建完整路径? [英] How to create full path with node's fs.mkdirSync?

查看:308
本文介绍了如何使用节点的fs.mkdirSync创建完整路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a full path if it doesn't exist.

代码如下:

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

只要只有一个子目录(例如"dir1"之类的newDest),此代码就可以很好地工作,但是当存在一个目录路径((dir1/dir2"))时,它将失败并显示 错误:ENOENT,没有这样的文件或目录

This code works great as long as there is only one subdirectory (a newDest like 'dir1') however when there is a directory path like ('dir1/dir2') it fails with Error: ENOENT, no such file or directory

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

I'd like to be able to create the full path with as few lines of code as necessary.

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

I read there is a recursive option on fs and tried it like this

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?

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

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

推荐答案

一种选择是使用 shelljs模块

npm安装shelljs

npm install shelljs

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

在该页面上:

可用选项:

Available options:

p:完整路径(如有必要,将创建中间目录)

p: full path (will create intermediate dirs if necessary)

正如其他人所指出的,还有其他更专注的模块.但是,在mkdirp之外,它还有大量其他有用的shell操作(例如grep等),并且可以在Windows和* nix

As others have noted, there's other more focused modules. But, outside of mkdirp, it has tons of other useful shell operations (like which, grep etc...) and it works on windows and *nix

这篇关于如何使用节点的fs.mkdirSync创建完整路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆