Cover image for Generate unique color code in javascript

Generate unique color code in javascript

rajnishkatharotiya profile image Rajnish Katharotiya ・2 min read

Photo by Nicole Wolf on Unsplash

The title sounds interesting, right? I mean it was for me to create or validate into local/server machine's directories.

Beforehand, let me welcome you in the series of Javascript Useful Snippets, here I'll be sharing some shortcodes and function which can help you to make your development faster and efficient. So, if you haven't read my previous posts check it out a profile now else please stay tuned to the end (I'm sure you will get something 😋) ...

Have you ever needed to create a directory from your app and before creation had to validate if this same-named directory exists or not? if yes, please share it via a comment on how you achieved it? I've one function defined to process this task. checkAndCreateDir() it takes a directory name as parameter, check if it's already created else create a new one. Let me share a snippet:-

const fs = require('fs');
const checkAndCreateDir = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);

That's it, just two lines to get the job done. Here I've used fs (file system - this module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.) to validate and create folder respectively with functions existsSync() and mkdirSync() from fs. In return, it's executed existsSync() with a directory name, if it'll return false then only mkdirSynce() will execute otherwise it'll return undefined.

Use is just as simple as it looks:


Note:- While running this function, or executing any function with the parameter value. We should make sure it's not empty. Here, before we pass "dir" to existsSync() or mkdirSync() we should check it has some value in it. and to check that I've one other snippet to introduce which allow us to check any type of data to validate if's empty or not, here it is...

const isEmpty = val => val == null || !(Object.keys(val) || val).length;

I found this snippet to useful for me, so thought to share it with you too. I hope you got something from here. if yes, please hit follow button 😅 (Thanks for that - btw I share every day something here please stay tuned to learn something new ).

Posted on Apr 19 by:

rajnishkatharotiya profile

Rajnish Katharotiya


JavaScript enthusiast, Front-end developer, Blogger & YouTuber (https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg)


markdown guide