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

 

You can create a directory if it doesn't exist in Node.js using the fs (file system) module. Here's an example of how to do it:

javascript
const fs = require('fs'); const directoryPath = './my-directory'; // Check if the directory exists if (!fs.existsSync(directoryPath)) { // If it doesn't exist, create it fs.mkdirSync(directoryPath); console.log(`Directory '${directoryPath}' created.`); } else { console.log(`Directory '${directoryPath}' already exists.`); }

In this example:

  1. We require the fs module to work with the file system.

  2. We specify the directoryPath variable to hold the path of the directory you want to create or check for existence.

  3. We use fs.existsSync(directoryPath) to check if the directory exists. If it doesn't exist, we proceed to create it.

  4. If the directory doesn't exist, we use fs.mkdirSync(directoryPath) to create it synchronously.

  5. We log a message indicating whether the directory was created or if it already exists.

Make sure to replace ./my-directory with the actual path of the directory you want to create. This code will create the directory if it doesn't exist and provide a message indicating the result.

Comments