Explain Codes LogoExplain Codes Logo

Node.js create folder or use existing

javascript
async-programming
error-handling
performance-optimization
Alex KataevbyAlex Kataev·Jan 21, 2025
TLDR

Check and create a directory (if it does not exist) promptly using Node.js's fs module:

const fs = require('fs'); const dir = './your/directory/path'; !fs.existsSync(dir) && fs.mkdirSync(dir, { recursive: true });

This checks if dir already exists, and if not, creates it, including any intermediate directories with { recursive: true }.

The asynchronous touch

Perform non-blocking operations with Node's fs module to handle directory creation. It keeps your application lively and responsive:

const fs = require('fs').promises; async function createDir(dir) { try { await fs.mkdir(dir, { recursive: true }); } catch (err) { if (err.code !== 'EEXIST') throw err; // Life's too short to worry about existing directories. } }

This approach allows you to create directories without blocking the event loop.

The art of error-handling and performance trade-offs

Error handling is an indispensable part of filesystem operations. With try-catch, you can handle those unexpected surprises that occur during directory creation like a pro:

try { fs.mkdirSync(dir, { recursive: true }); } catch (err) { // Oops! We've got an error. Name it & shame it. console.error(`Something bad happened: ${err.code}, Message: ${err.message}`); if (err.code === 'EACCES') { // Warning! Warning! We are in permission error territory } else if (err.code === 'EEXIST') { // What's that? The directory already exists. Interesting. } else { // We've entered the unknown error zone folks. Time to call the superheroes (or debug) } }

When performance is a concern, avoiding the redundancies like calling fs.stat() or fs.existsSync() before fs.mkdir() or fs.mkdirSync(), can be super beneficial.

To be or not to be: the case of directory existence

Sometimes you need to be Sherlock Holmes and inspect a directory's existence before creating it:

const fs = require('fs'); const dir = './path/to/your/dir'; if (!fs.existsSync(dir)) { // The directory does not exist, time to create one fs.mkdirSync(dir, { recursive: true }); } else { // So, the directory does exist. Now what's your next adventure? }

Bringing in the big guns: third-party modules

Third-party modules like mkdirp expands the capabilities of the native fs module making your life a whole lot easier in the world of Node:

const mkdirp = require('mkdirp'); mkdirp(dir).then(made => console.log(`Directory ${made} just popped into existence!`)).catch(err => { console.error(`Creating directory felt like Infinity War: ${err.message}`); }); // Feels like wielding Thor's hammer, doesn't it?

Error code literacy: A must for Node.js developers

Knowing your error codes is like owning the infinity stones. They keep you empowered to deal with all types of filesystem anomalies like a true Thanos (minus the destruction hopefully).

Synchronous vs. Asynchronous: making the right choice

Choosing between synchronous and asynchronous methods is often a battle between code simplicity and non-blocking operations. Balance, like all things, should be achieved.

Path handling: right tools for the job

The built-in path module in Node.js forms the backbone for efficient path handling.

const path = require('path'); const dir = path.join(__dirname, 'my', 'new', 'directory'); // Now you can use dir with fs.mkdirSync or fs.promises.mkdir. // And the directory is created right where it should be. Easy peasy lemon squeezy.

path.join ensures you've got the right string for any OS you're dealing with.