Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

javascript - Node.js创建文件夹或使用现有文件夹(Node.js create folder or use existing)

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() .

(我已经阅读了Node.js的文档,除非我错过了某些内容,否则它不会告诉某些操作(尤其是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);
    }
});

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?

(检查代码EEXIST是否正确知道文件夹已存在?)

I know I can do fs.stat() before making the directory, but that would already be two hits to the filesystem.

(我知道我可以在创建目录之前执行fs.stat() ,但这已经是对文件系统的两次打击。)

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.

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

  ask by Joseph translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Good way to do this is to use mkdirp module.

(做到这一点的好方法是使用mkdirp模块。)

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

(如果mkdirp创建目录路径失败,则会设置错误err 。)

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

    // path exists unless there was an error

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...