nodejs create folder if not exist
To create a folder in Node.js if it doesn't already exist, you can follow these steps:
Import the
fs
module: To interact with the file system in Node.js, you need to import the built-infs
module. This module provides various methods and properties to work with files and directories.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 returnstrue
if the directory exists, andfalse
otherwise.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 arecursive
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.