How to create a directory if it doesn"t exist using Node.js

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to create a directory if it doesn"t exist using Node.js

How to Create a Directory if it Doesn't Exist 💻📁

So you want to create a directory using Node.js, but only if it doesn't already exist? You've come to the right place! In this blog post, we'll guide you through the process and provide easy solutions to tackle this common issue. Let's get started! 🚀

The Problem: Creating a Directory Conditionally 🤔

Imagine you have a Node.js script that needs to create a directory for file uploads. However, you don't want to accidentally overwrite any existing directories. So how do you go about creating a directory only if it doesn't already exist? 🤷‍♂️

The Old Approach: Using Deprecated Methods ❌

In the code snippet you provided, path.existsSync and fs.mkdirSync are used. However, it's important to note that these methods are deprecated and no longer recommended for use. So we'll explore a more modern approach using the current version of Node.js. 😉

The Modern Solution: Using fs Promises 🆕✨

Node.js provides an updated version of the fs module that supports promises, making our code more readable and efficient. Let's take a look at the revised solution using the fs.promises API: 👇

const fs = require('fs');

async function createDirectoryIfNotExist(dirPath) {
  try {
    await fs.promises.access(dirPath);
  } catch (error) {
    await fs.promises.mkdir(dirPath, { recursive: true, mode: 0o744 });
  }
}

const uploadDirectory = __dirname + '/upload';
createDirectoryIfNotExist(uploadDirectory)
  .then(() => {
    console.log('Directory created successfully!');
  })
  .catch((error) => {
    console.error('Failed to create directory:', error);
  });

Breaking Down the Code ✂️

  1. We import the fs module, Node.js' file system module, which provides us with various methods to manipulate files and directories.

  2. We define an async function called createDirectoryIfNotExist which takes the dirPath as a parameter.

  3. Inside the function, we use fs.promises.access to check if the directory already exists. If it does, the function execution stops. Otherwise, it proceeds to the catch block.

  4. In the catch block, we use fs.promises.mkdir to create the directory at dirPath. The recursive option enables the creation of nested directories, and the mode option sets the directory's permissions to 0o744, which allows full permission for the script and read access for others.

  5. Finally, we call the createDirectoryIfNotExist function with the desired directory path (uploadDirectory in this example). We handle the successful directory creation with the then block and handle any errors with the catch block.

Time to Take Action! 🚀

Now that you've seen how to create a directory if it doesn't exist using Node.js, it's time to put this knowledge into practice! Feel free to use the provided code as a starting point and adapt it to your specific needs. If you encounter any issues or have further questions, don't hesitate to ask in the comments section below! Let's make directory creation a breeze! 💪💡

Your Turn! 🙌

Have you ever faced difficulties creating directories programmatically? How did you tackle the issue? Share your experiences and solutions with us in the comments. We'd love to hear from you! 😊💬

Keep exploring, learning, and coding! Until next time, happy coding! 🎉👩‍💻👨‍💻

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my