PASSWORD RESET

Your destination for complete Tech news

how to create a directory if it doesn’t exist in node js?

392 0
2 min read

To create a directory in Node.js, you can use the fs (file system) module and the fs.mkdir() function. This function takes a path and an optional options object, and creates the directory at the specified path.

Here’s an example of how to create a directory if it doesn’t exist:

const fs = require('fs');

const dir = './mydir';

if (!fs.existsSync(dir)) {
  fs.mkdir(dir, (err) => {
    if (err) {
      console.error(`Error creating directory ${dir}: ${err}`);
    } else {
      console.log(`Directory ${dir} created successfully`);
    }
  });
}

In this example, we first check if the directory exists using the fs.existsSync() function, which synchronously checks for the existence of a file or directory. If the directory does not exist, we use the fs.mkdir() function to create it. The fs.mkdir() function takes a callback function as an argument, which is called when the operation is complete. If the directory was successfully created, the callback function will be called with a null error object; otherwise, it will be called with an error object that describes the error that occurred.

Note: The fs.mkdir() function is asynchronous and may execute in the background after the call returns. If you need to perform additional operations on the directory after it is created, you should do so in the callback function.

Alternatively, you can use the fs.mkdirSync() function to create a directory synchronously. This function works in a similar way to fs.mkdir(), but it blocks execution until the operation is complete.

const fs = require('fs');

const dir = './mydir';

if (!fs.existsSync(dir)) {
  try {
    fs.mkdirSync(dir);
    console.log(`Directory ${dir} created successfully`);
  } catch (err) {
    console.error(`Error creating directory ${dir}: ${err}`);
  }
}

In this example, we use a try-catch block to handle any errors that may occur while creating the directory. If the directory was successfully created, the console.log() statement will be executed; otherwise, the console.error() statement will be executed with the error object as an argument.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.