JavaScript Development Space

How to Create a Directory if It Does Not Exist in Node.js

In Node.js, you can create a directory if it doesn't exist using the fs (File System) module. Here's how you can do it:

1. Using fs.mkdir:

You can use the fs.mkdir function to create a directory. If the directory already exists, it will throw an error. To handle the case where the directory may or may not exist, you can use the fs.access function to check if the directory exists before attempting to create it.

js
1 const fs = require('fs');
2 const path = require('path');
3
4 const directory = 'path/to/directory';
5
6 // Check if the directory exists
7 fs.access(directory, fs.constants.F_OK, (err) => {
8 if (err) {
9 // Directory doesn't exist, create it
10 fs.mkdir(directory, { recursive: true }, (err) => {
11 if (err) {
12 console.error('Error creating directory:', err);
13 } else {
14 console.log('Directory created successfully');
15 }
16 });
17 } else {
18 console.log('Directory already exists');
19 }
20 });

In this code:

  • We use fs.access to check if the directory exists. If it doesn't exist, it will throw an error, which we catch to create the directory.

  • We use fs.mkdir to create the directory. The recursive: true option ensures that parent directories are created recursively if they don't exist.

Using fs.promises.mkdir (Node.js v10 and above):

If you are using Node.js version 10 or above, you can use the fs.promises API for asynchronous file system operations without using callbacks.

js
1 const fs = require('fs').promises;
2 const path = require('path');
3
4 const directory = 'path/to/directory';
5
6 // Create the directory if it doesn't exist
7 fs.mkdir(directory, { recursive: true })
8 .then(() => console.log('Directory created successfully'))
9 .catch((err) => console.error('Error creating directory:', err));

This code achieves the same result as the previous example but uses promises for asynchronous operations.

Conclusion:

Both methods allow you to create a directory if it doesn't exist using Node.js. Choose the method that best fits your coding style and the Node.js version you're targeting.

JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.