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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 14:51:29

问题


I am trying to create folder hierarchy named current year inside create another folder with name current month and then again inside that folder create another folder with name current date.

For example : Today's date is 2016-05-02, So the folder should be create if not already exist like following structure

2016->05->02


回答1:


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

});



回答2:


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 :) ");
  })
});


来源:https://stackoverflow.com/questions/36589329/how-to-create-folder-hierarchy-of-year-month-date-if-not-exist-in-node-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!