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
- NodeJS >= v10 LTS.
- Working knowledge of
promises
andasync await
.
That's it 😊
TLDR Code:
const { mkdir } = require('fs').promises;
try {
await mkdir('folderPath');
} catch (e) {}
Explanation
We import promise-based version of mkdir from
fs.promises
. Read my article about Simple code with fs.promises and async await.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) {}
}
Hope it helped!
Top comments (4)
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?
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?
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 ;-)
Exactly! Not so catchy anymore