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. You can also check other posts on npm command deprecate option is deprecated

How to 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.


fs.mkdirSync(path, [options]);

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 to provide below code

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

Similarly, It provides the mkdir() function which is an asynchronous version of a mkdirSync.

const directorypath="folder";
fs.access(directorypath, (error) => {
fs.mkdir(directorypath, { recursive: true }, (err,data) => {
    if (err) throw err;
    console.log("folder created",true)