The Node.js fs native module provides several useful methods that you can use to work with directories. 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. Here is an example:

const fs = require('fs');

// directory to check if exists
const dir = './uploads';

// check if directory exists
if (fs.existsSync(dir)) {
    console.log('Directory exists!');
} else {
    console.log('Directory not found.');
}

The existsSync() method returns true if the path exists, false otherwise.

If you prefer to use an asynchronous check, use the fs.access() method instead. This method takes a path as input and tests the user's permissions.

Let us look at the below example that uses fs.access() to check if the given directory exists:

const fs = require('fs');

// directory to check if exists
const dir = './uploads';

// check if directory exists
fs.access(dir, (err) => {
    console.log(`Directory ${err ? 'does not exist' : 'exists'}`);
});

Take a look at this guide to learn more about reading and writing files in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: