LEARNNode CLI Automation

IIFE — Immediately Invoked Function Expression

So far you have seen that whenever I am building a Node.js CLI, I am writing all of my code in the index.js file. This is not right because I am polluting the global namespace of Node.js. Also, there is a lot of code pilling in this file.

To take care of it, I am going to refactor some code. Then I am going to use IIFE (Immediately Invoked Function Expression) to solve the polluting global namespace problem. So without any further ado, let's jump in!

Refactoring Code

I like to follow this convention where I put all of my supporting files inside this utils directory. So the first thing you should do is create a utils directory in the root of your CLI project. I am going to do the same thing.

Now create an init.js file inside this directory. This file will have all the code that is related to the initialization of the CLI.

In my name CLI, I am going to require this init.js in the index.js file. Then I am going to cut all the initialization code of my name CLI and paste it inside the init.js file.

CLI initialization

Working With IIFE

There is still a problem that all of our code in the index.js file is in the global namespace of Node.js. To take care of it, I am going to show you how you can use an IIFE. As the name suggests, you don't need to call an IIFE. It is invoked automatically when the file is executed.

The syntax of IIFE is quite simple.

(() => {
})()

You need to add all of your code inside the curly brackets {} and it will be executed automatically. If you need some parameters in your CLI, you can pass them inside the parentheses before the fat arrow. You can read more about them here.

For now, I am going to use the IIFE to create a block scope for all of my CLI code inside index.js.

IIFE used

Now I am going to test my CLI again to see if everything is working correctly.

CLI initialization

As you can see that my CLI is working and we have also taken care of our global namespace problem.

Wrapping Up

IIFE is a good option when you need to execute some code without calling it. Also, refactoring your code into different modules help the developers understand your work even more. So go ahead and do all this and write some useful CLIs.

Posted by Saad (It's a work in progress: Needs copy editing review by Awais.)