Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node - Check to see if a directory exists

Tags:

node.js

This should be a fairly simple one to answer I would hope, however it's got me stumped - maybe I've been staring at too much code today!

I am trying to do a simple if statement which checks to see if a folder exists. If the folder doesn't exist, make it, if it does, delete the content.

The problem I am having is that if the directory doesn't exist, then the callback (stats) is undefined. With fs.exist it would be quite simple, but since its deprecated, I wanted to ensure this was future proofed.

var seriesid = 5;
      fs.stat("temp/" + seriesid, function (err, stats){
        if(!stats.isDirectory()){
          fs.mkdir("temp/" + seriesid);
          console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
          callback();
        }
        else if (err != 'ENOENT') {
          callback(err);
        }
        else {
          // TODO: Folder exists, delete contents
          console.log('Does exist');
          callback();
        }
      });

Any help on how to accomplish this would be appreciated

like image 356
K20GH Avatar asked Mar 07 '16 16:03

K20GH


People also ask

How do you check if a directory exists in JS?

The simplest way to check if a certain directory exists in Node. js is by using the fs. existsSync() method. The existsSync() method asynchronously checks for the existence of the given directory.

How do you check file is exist or not in node JS?

The easiest way to test if a file exists in the file system is by using the existsSync method. All you need to do is pass the path of the file to this method. The existsSync method will return true if the file exists and else it'll return false.

What is FS existsSync?

Synchronously tests whether or not the given path exists by checking with the file system.

Which of the following will synchronously check if a file directory exists?

The existsSync method of the fs module is used to check if a file or directory exists in the file system.


1 Answers

Check err first. Then check isDirectory()

fs.stat("temp/" + seriesid, function (err, stats){
  if (err) {
    // Directory doesn't exist or something.
    console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
    return fs.mkdir("temp/" + seriesid, callback);
  }
  if (!stats.isDirectory()) {
    // This isn't a directory!
    callback(new Error('temp is not a directory!'));
  } else {
    console.log('Does exist');
    callback();
  }
});
like image 50
Sukima Avatar answered Oct 05 '22 23:10

Sukima