thevan
thevan

Reputation: 10354

How to create a folder in a path?

I want to upload a file to a path under a specific user folder. For example, consider I want to upload a file in D Drive.

The path will be like D:/User1.     //User1 is a User Folder Name

I used to pass both the Drive and Folder name as a variable.

For a new user, the user folder will not exists, so at that time I need to create a folder for the user in the D Drive. If the user already has the folder then I dont want to create.

How to do this using node.js?

Upvotes: 2

Views: 191

Answers (3)

Florian Margaine
Florian Margaine

Reputation: 60767

You could use the mkdirp module, it handles creating recursive directories if they don't exist etc.

Sample code:

var mkdirp = require('mkdirp');
mkdirp('/tmp/foo/bar/baz', function (err) {
    if (err) console.error(err)
    else console.log('pow!')
});

Upvotes: 1

marioosh
marioosh

Reputation: 28566

  var fs = require('fs');
  var path = 'D:\\user1';

  fs.stat(path, function(err, stats){
     if(!err && stats) {
        // folder or file exists
     } else {
        fs.mkdir(path, function(err){
           if(!err) {
              // folder created
           } else {
              // something goes wrong
           }
        });
     }
  });

Upvotes: 1

neelsg
neelsg

Reputation: 4842

You can do this using the File System module using the mkdir command

Upvotes: 1

Related Questions