NodeJS Create folder if not exists in 3 lines - No dependencies
PuruVJ

PuruVJ @puruvj

Location:
Jaipur, Rajasthan, India
Joined:
Sep 30, 2019

NodeJS Create folder if not exists in 3 lines - No dependencies

Publish Date: Jan 18 '21
13 4

Read this post in dark or mid-day theme

Here's a very simple trick to create a folder if it doesn't exists (Or ensure if a folder exists) in NodeJS. Just 3 lines, no dependencies

Minimum requirements

  1. NodeJS >= v10 LTS.
  2. Working knowledge of promises and async await.

That's it 😊

TLDR Code:

const { mkdir } = require('fs').promises;

try {
  await mkdir('folderPath');
} catch (e) {}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. We import promise-based version of mkdir from fs.promises. Read my article about Simple code with fs.promises and async await.

  2. We actually create the folder with the await mkdir('folderPath').

Note: We are using an await here, so it's necessary for this code to be in an async function, or you can also use the Top Level Await feature in NodeJS >= 14.8.0. Read my article about why Top level Await is AWESOME!! 😍

Why wrap it in try-catch?

Remember: We're trying to create a folder if it doesn't exists. That means there's a fair chance it may already exists, in which case mkdir will throw an error, and will stop the rest of code from executing. We don't want that now, do we? 😉

So if mkdir works perfectly, good, means the folder didn't exist, so it was created. But if it throws error, try catch will simply catch the error, ignore it, and move on to the rest of the code.

Simple!

As a utility function

Make this snippet part of your utility belt 👇

/**
 * Ensure that a folder exists
 * @param {string} folderPath
 */
async function ensureFolder(folderPath) {
  try {
    await mkdir(folderPath);
  } catch (e) {}
}
Enter fullscreen mode Exit fullscreen mode

Hope it helped!

Comments 4 total

  • Hendrik Richert
    Hendrik RichertJan 18, 2021

    You might want to check for the type of exception you receive instead of just ignoring all of them. For example, you probably want to report a permission error when trying to create a directory, right?

    • PuruVJ
      PuruVJJan 18, 2021

      Thank you for the advice. I didn't think of that. Would fire right back in cloud environments 😅

      Is there any reference of errors that I can look up for the error codes?

      • Hendrik Richert
        Hendrik RichertJan 18, 2021

        Thats a good question :-) I couldn't find a list of possible exceptions for promises.mkdir
        My proposed solution would be to not catch any exceptions, but instead do a check if the dir exists first, and only if it doesn't try to create it. In that case you would be safe to report any errors back to the user.

        But then again that would ruin your 3 lines example ;-)

        • PuruVJ
          PuruVJJan 18, 2021

          But then again that would ruin your 3 lines example ;-)

          Exactly! Not so catchy anymore

Add comment