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
  fs.mkdirSync(directoryPath);

  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
fs.promises.mkdir(directoryPath)
  .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.