How to Check if a Directory Exists using Node
Table of Contents
Because Node runs on the server, it has access to the file system.
Sometimes you need to know if a directory exists or not before continuing on with your program.
In this post, we'll learn how we can asynchronously check if a directory exists using Node.
How to check if a directory exists
The easiest way to check if a directory exists is to import the fs
module and use the access
method.
This method allows you to asynchronously attempt to access the directory at the path you provide.
Let's say this is the path you want to check:
JAVASCRIPTconst path = "/path/to/directory";
Call the access
method with the path as the first argument:
JAVASCRIPTimport { promises as fs } from "fs";
const path = "/path/to/directory";
const exists = async path => {
try {
await fs.access(path);
} catch (error) {
return false;
}
return true;
};
const results = await exists(path);
console.log(results);
If the directory exists, the access
method will execute successfully and our exists
method will return true
.
If it does not, an exception will be thrown and our exists
method will return false
.
If you don't want to use async
/await
, you can alternatively use the access
method by passing it a callback function:
JAVASCRIPTimport fs from "fs";
const path = "/path/to/directory";
fs.access(path, error => {
const exists = !error;
console.log(`Exists ${exists}`);
});
Conclusion
In this post, we learned how to check if a directory exists in Node asynchronously.
You can either use async
/await
or pass a callback function to the access
method.
Thanks for reading this post!
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Getting User Location using JavaScript's Geolocation API
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- How To Create a Modal Popup Box with CSS and JavaScript