Create Directory When Writing To File In Node.js

前端 未结 9 1421
情话喂你
情话喂你 2021-01-30 09:44

I\'ve been tinkering with Node.js and found a little problem. I\'ve got a script which resides in a directory called data. I want the script to write some data to

9条回答
  •  太阳男子
    2021-01-30 10:30

    My advise is: try not to rely on dependencies when you can easily do it with few lines of codes

    Here's what you're trying to achieve in 14 lines of code:

    fs.isDir = function(dpath) {
        try {
            return fs.lstatSync(dpath).isDirectory();
        } catch(e) {
            return false;
        }
    };
    fs.mkdirp = function(dirname) {
        dirname = path.normalize(dirname).split(path.sep);
        dirname.forEach((sdir,index)=>{
            var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
            if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
        });
    };
    

提交回复
热议问题