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:
We require the
fs
module to work with the file system.We specify the
directoryPath
variable to hold the path of the directory you want to create or check for existence.We use
fs.existsSync(directoryPath)
to check if the directory exists. If it doesn't exist, we proceed to create it.If the directory doesn't exist, we use
fs.mkdirSync(directoryPath)
to create it synchronously.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
Post a Comment