How to use Node.js fs.mkdirSync() In Node.js

Let’s create a new directory using fs.mkdirSync() method. Initially, we have single file index.js, as we can see in the given image.

Example:

Node
const fs1 = require("fs-extra");

// Node.js program to demonstrate the
// fs.mkdirSync() method

const fs = require("fs");

const path = require("path");

// Using fs.exists() method to
// Check that the directory exists or not
console.log("Checking for directory" + path.join(__dirname, "Tisu"));
fs.exists(path.join(__dirname, "Tisu"), (exists) => {
  console.log(exists ? "The directory already exists" : "Not found!");
});

// Using fs.mkdirSync() method
// To create the directory recursively
fs.mkdirSync(path.join(__dirname, "Tisu"), true);

// Using fs.exists() method to
// Check that the directory exists or not
fs.exists(path.join(__dirname, "Tisu"), (exists) => {
  console.log(exists ? "The directory already exists" : "Not found!");
});

Output:

How to Create a Directory using Node.js ?

In this article, we will create a directory using NodeJS.

NodeJS has Filesystem(fs) core module, which enables interacting with the file system, has Node.js fs.mkdir() method or Node.js fs.mkdirSync() method method, to create new directory /parent directory.

Prerequisites:

The approaches for creating a directory using Node are mentioned below:

Table of Content

  • Using Node.js fs.mkdir()
  • Using Node.js fs.mkdirSync()

Similar Reads

Using Node.js fs.mkdir()

Let’s create a new directory using fs.mkdir() method. Initially, we have single file index.js, as we can see in the given image....

Using Node.js fs.mkdirSync()

Let’s create a new directory using fs.mkdirSync() method. Initially, we have single file index.js, as we can see in the given image....

Conclusion

Creating a directory using Node.js involves using the fs module’s mkdir or mkdirSync methods. These methods allow asynchronous or synchronous directory creation, respectively. Ensure to handle errors properly, especially for asynchronous operations, to prevent runtime issues and enhance the robustness of your Node.js application....

Contact Us