Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a directory exists in node.js?

Tags:

node.js

I'd like to save files received from json object in a REST API app and here is the code:

 router.post('/addphoto',  checkAuth, (req, res)=> {
  let filename = Math.floor(Math.random() * 100000);
   let dir = './uploads/' + req.user.id;

//Not sure about this
if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}

base64String = req.body.file;
let base64Image = base64String.split(';base64,').pop();
let filePath = dir + "/" + filename

fs.writeFile( filePath, base64Image, {encoding: 'base64'}, function(err) {
console.log('File created');
});
...

It does the job but I've read that existsSync is deprecated, and also I'm not sure if it's a good idea to use sync code inside a router which is async by nature.

So I'm wondering what is the idiomatic way to do so in such circumstances?

like image 954
Babr Avatar asked Oct 20 '25 04:10

Babr


2 Answers

You can use access

fs.access(myDir, function(err) {
  if (err && err.code === 'ENOENT') {
    fs.mkdir(myDir); //Create dir in case not found
  }
});
like image 186
Mohammad Raheem Avatar answered Oct 22 '25 19:10

Mohammad Raheem


I've read that existsSync is deprecated

It isn't. See the manual:

fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.


I'm not sure if it's a good idea to use sync code inside a router which is async by nature.

There's nothing intrinsically wrong about doing something synchronous inside something that is asynchronous — most JS is synchronous — but it does mean that the feature would block the event loop while looking at the file system, and looking at the file system is a relatively time-consuming operation, so it wouldn't be good for performance.

Your code might not need that level of performance, but that's a judgement call we can't make for you.

exists is right next to existsSync in the manual and says:

Deprecated: Use fs.stat() or fs.access() instead.

So pick one of those.

access has an example:

// Check if the file exists in the current directory.
fs.access(file, fs.constants.F_OK, (err) => {
  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
like image 38
Quentin Avatar answered Oct 22 '25 18:10

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!