nodejs create folder if not exist

To create a folder in Node.js if it doesn't already exist, you can follow these steps:

  1. Import the fs module: To interact with the file system in Node.js, you need to import the built-in fs module. This module provides various methods and properties to work with files and directories.

  2. Use the fs.existsSync() method: This method checks if a given directory exists or not. Pass the path of the directory you want to check as an argument to this method. It returns true if the directory exists, and false otherwise.

  3. Use the fs.mkdirSync() method: If the directory doesn't exist, you can use this method to create it. Pass the path of the directory you want to create as the first argument. Optionally, you can also pass a recursive flag as the second argument to create parent directories if they don't exist. This method will throw an error if the directory already exists.

Here's an example of how you can create a folder if it doesn't exist in Node.js:

const fs = require('fs');

const folderPath = 'path/to/folder';

if (!fs.existsSync(folderPath)) {
  fs.mkdirSync(folderPath, { recursive: true });
}

In this example, replace 'path/to/folder' with the actual path where you want to create the folder. The recursive flag allows you to create nested directories if needed.

By following these steps, you can create a folder in Node.js if it doesn't already exist.