Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js create folder or use existing

People also ask

How do I make a FS folder?

Create a new folderUse fs. mkdir() or fs. mkdirSync() or fsPromises. mkdir() to create a new folder.

Which method is used to create a directory in node JS?

mkdir() Method. The fs. mkdir() method i Node. js is used to create a directory asynchronously.


Good way to do this is to use mkdirp module.

$ npm install mkdirp

Use it to run function that requires the directory. Callback is called after path is created or if path did already exists. Error err is set if mkdirp failed to create directory path.

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

    // path exists unless there was an error

});

Edit: Because this answer is very popular, I have updated it to reflect up-to-date practices.

Node >=10

The new { recursive: true } option of Node's fs now allows this natively. This option mimics the behaviour of UNIX's mkdir -p. It will recursively make sure every part of the path exist, and will not throw an error if any of them do.

(Note: it might still throw errors such as EPERM or EACCESS, so better still wrap it in a try {} catch (e) {} if your implementation is susceptible to it.)

Synchronous version.

fs.mkdirSync(dirpath, { recursive: true })

Async version

await fs.promises.mkdir(dirpath, { recursive: true })

Older Node versions

Using a try {} catch (err) {}, you can achieve this very gracefully without encountering a race condition.

In order to prevent dead time between checking for existence and creating the directory, we simply try to create it straight up, and disregard the error if it is EEXIST (directory already exists).

If the error is not EEXIST, however, we ought to throw an error, because we could be dealing with something like an EPERM or EACCES

function ensureDirSync (dirpath) {
  try {
    return fs.mkdirSync(dirpath)
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
}

For mkdir -p-like recursive behaviour, e.g. ./a/b/c, you'd have to call it on every part of the dirpath, e.g. ./a, ./a/b, .a/b/c


If you want a quick-and-dirty one liner, use this:

fs.existsSync("directory") || fs.mkdirSync("directory");

The node.js docs for fs.mkdir basically defer to the Linux man page for mkdir(2). That indicates that EEXIST will also be indicated if the path exists but isn't a directory which creates an awkward corner case if you go this route.

You may be better off calling fs.stat which will tell you whether the path exists and if it's a directory in a single call. For (what I'm assuming is) the normal case where the directory already exists, it's only a single filesystem hit.

These fs module methods are thin wrappers around the native C APIs so you've got to check the man pages referenced in the node.js docs for the details.


You can use this:

if(!fs.existsSync("directory")){
    fs.mkdirSync("directory", 0766, function(err){
        if(err){
            console.log(err);
            // echo the result back
            response.send("ERROR! Can't make the directory! \n");
        }
    });
}