Hi Guy’s Welcome to Proto Coders Point. In this NodeJS Article let’s learn How to create a directory(folder) if it doesn’t exist in nodeJS using file system (fs) library.
Creating directory using NodeJS
I will assume you already have a node project opened or created.
As I said to work with File System like creating folder, reading files from a folder we require NodeJS fs library.
Install fs module using below command
node install fs
Check if the folder already exist in nodejs
Before creating a directory in any working directory, We must first check if the folder that we want to create already exist or no. If don’t exist we can create it. To check if folder exist we can make use of fs existSync(<folderName>) the return type is true or false.
fs.existsSync(rootFolder)
Creating directory in nodejs
Then to create directory/folder we can make use of fs mkdirSync(<folderPath>)
fs.mkdirSync(folderpath);
In below Code, I have a API Router “/createFolder” been created using ExpressJS, user can send a folderName that he want to create. So now assume I want to create a root folder with a subfolder in it, So first I need to check if rootFolder exist if yes then check if inside root folder subfolder exist or no if no then create the subfolder(The user is willing to create ). Now another scenario is the else part i.e. if rootFolder don’t exist we must create it and then create subFolder in it.
router.post("/createFolder", async (req, res) => { const folderName = req.body.folderName; if (!folderName) { return res.json({ status: false, message: "Folder Name is Mandatory" }); } const rootFolder = "rootFolder"; const folderpath = `${rootFolder}/${folderName}`; try { if (fs.existsSync(rootFolder)) { if (!fs.existsSync(folderpath)) { fs.mkdirSync(folderpath); return res.json({ status: true, success: "Directory created" }); } } else { fs.mkdirSync(rootFolder); if (!fs.existsSync(folderpath)) { fs.mkdirSync(folderpath); return res.json({ status: true, success: "Directory/Folder created" }); } } return res.json({ status: true, success: "Directory/Folder Already Exist" }); } catch (error) { console.log(error); } });