How to Create a directory in Nodejs with examples

This article covers multiple ways to create a directory Nodejs. One way using fs.mkdir using an asynchronous callback, and Another way using mkdirSync

How do you create a directory if it doesn’t exist using node JS?

Sometimes, We need to check if a folder exists or not. Nodejs provides an inbuilt fs module that provides multiple functions.

This is an asynchronous version of the checking folder that exists or not.



path: the path of the folder to create options: recursive to true or false.

const fs = require("fs");

if(fs.existsSync("folder") || fs.mkdirSync("folder")){
    console.log("Folder exists")

The above code does not work if the path contains folder1/folder2.

For this we need provide below code

const fs = require("fs");
if(fs.existsSync("folder") || fs.mkdirSync("folder",{recursive:true})){
    console.log("Folder exists")

Similarly, It provides mkdir() function which is aschronous version of an mkdirSync.

const directorypath="folder";
fs.access(directorypath, (error) => {
fs.mkdir(directorypath, { recursive: true }, (err,data) => {
    if (err) throw err;
    console.log("folder created",true)
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.