How to create folder hierarchy of year -> month ->

2019-03-22 18:01发布

问题:

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


标签: node.js fs