Node.js创建文件夹或使用现有文件夹 [英] Node.js create folder or use existing

查看:1162
本文介绍了Node.js创建文件夹或使用现有文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读过Node.js的文档,除非我遗漏了某些内容,否则它不会告诉某些操作中包含的参数,特别是 fs.mkdir() 。正如您在文档中看到的那样,它并不是很多。

I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdir(). As you can see in the documentation, it's not very much.

目前,我有这段代码,它尝试创建一个文件夹或使用现有文件夹:

Currently, I have this code, which tries to create a folder or use an existing one instead:

fs.mkdir(path,function(e){
    if(!e || (e && e.code === 'EEXIST')){
        //do something with contents
    } else {
        //debug
        console.log(e);
    }
});

但我想知道这是正确的方法吗?正在检查代码 EEXIST 是否知道该文件夹已存在的正确方法?我知道在创建目录之前我可以做 fs.stat(),但这已经是文件系统的两次点击。

But I wonder is this the right way to do it? Is checking for the code EEXIST the right way to know that the folder already exists? I know I can do fs.stat() before making the directory, but that would already be two hits to the filesystem.

其次,是否有完整的或至少更详细的Node.js文档,其中包含有关错误对象包含的详细信息,表示哪些参数等。

Secondly, is there a complete or at least a more detailed documentation of Node.js that contains details as to what error objects contain, what parameters signify etc.

推荐答案

这样做的好方法是使用 mkdirp 模块。

Good way to do this is to use mkdirp module.

$ npm install mkdirp

使用它来运行需要该目录的函数。在创建路径或路径确实存在之后调用回调。如果mkdirp无法创建目录路径,则设置错误错误

Use it to run function that requires the directory. Callback is called after path is created or if path did already exists. Error err is set if mkdirp failed to create directory path.

var mkdirp = require('mkdirp');
mkdirp('/tmp/some/path/foo', function(err) { 

    // path exists unless there was an error

});

这篇关于Node.js创建文件夹或使用现有文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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