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:
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()