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

Better Stack Team
Updated on March 11, 2024

In Node.js, you can use the fs (file system) module to create a directory if it doesn't exist. The fs module provides the mkdir function for creating directories. Here's an example:

const fs = require('fs');

const directoryPath = './myDirectory';

// Check if the directory exists
if (!fs.existsSync(directoryPath)) {
  // If it doesn't exist, create the directory

  console.log(`Directory '${directoryPath}' created.`);
} else {
  console.log(`Directory '${directoryPath}' already exists.`);

In this example:

  • The fs.existsSync() function checks if the directory already exists.
  • If the directory doesn't exist (!fs.existsSync(directoryPath)), the fs.mkdirSync() function is used to create the directory synchronously.
  • If the directory already exists, a message is logged indicating that the directory is already present.

If you prefer an asynchronous approach, you can use the fs.promises.mkdir() function:

const fs = require('fs').promises;

const directoryPath = './myDirectory';

// Use fs.promises.mkdir() to create the directory asynchronously
  .then(() => console.log(`Directory '${directoryPath}' created.`))
  .catch(err => console.error(`Error creating directory: ${err.message}`));

Note that the asynchronous method returns a promise, and you can use .then() to handle success and .catch() to handle errors.

Choose the synchronous or asynchronous approach based on your application's requirements. If you're working with other asynchronous operations, using the asynchronous method might be more appropriate to avoid blocking the event loop.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github