How to create folder hierarchy of year -> month -> date if not exist in node.js

烂漫一生 提交于 2019-12-03 10:14:53
KFE

See this previously answered question

Good way to do this is to use mkdirp module.

$ npm install mkdirp

Then use it to run function that requires the directory. Callback is called after path is created (if it didn't already exists). Error is set if mkdirp failed to create directory path.

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

    // path was created unless there was error

});

The best solution would be to use the npm module called node-fs-extra. The main advantage is that its built on top of the module fs, so you can have all the methods available in fs as well. It has a method called mkdir which creates the directory you mentioned. If you give a long directory path, it will create the parent folders automatically. The module is a super set of npm module fs, so you can use all the functions in fs also if you add this module.

one example

var fse = require('fs-extra')
var os = require('os')

function getTempPath() {
  return os.tmpdir();
}

mymodule.get('/makefolder',function(req,res){

  var tempfolder = getTempPath();
  var myfolder = tempfolder + '/yearfolder/monthfolder/datefolder/anyotherfolder';

  fse.mkdirs(myfolder, function (err) {
    if (err) return res.json(err)
    console.log("success!")
    res.json("Hurray ! Folder created ! Now, Upvote the solution :) ");
  })
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!