LEARNNode CLI Automation

Why Build CLIs With JavaScript

I have always said that one of the best perks of being a developer is that you can automate a lot of your grunt work. A great number of developers prefer to use the shell script to build such tools. But what if instead of the shell script, you use JavaScript to build such tools.

JavaScript is easy to learn and almost every developer has worked with it at some point in their careers. So let’s take a look at why you should use JavaScript to build CLI automation tools.

Easy To Write

When you are working with the shell script, you have to write so much odd-looking code. For instance, if you need to find the size of a file, the code of it will look something like this in the shell script.

function fs() {
if du -b /dev/null > /dev/null 2>&1; then
local arg=-sbh;
else
local arg=-sh;
fi
if [[ -n "[email protected]" ]]; then
du $arg -- "[email protected]";
else
du $arg .[^.]* ./*;
fi;
}

If you have never worked with shell scripts before, you will find this whole thing extremely confusing. And if I do the same thing in JavaScript now, it will look something like this.

const fs = require('fs');
function getFileSizeInBytes(filename) {
const stats = fs.statSync(filename);
const fileSizeInBytes = stats['size'];
return fileSizeInBytes;
}
console.log(getFileSizeInBytes(`${process.cwd()}/file`), `bytes`);

You can easily understand this code. I am importing the file system module and then using its statSync function to get all the stats of the file. And lastly, I am saving the file size in bytes in a separate variable and returning it.

npmjs

This might be the biggest factor that counts for using JavaScript for CLI automation. npmjs.com has more than 20 Billion packages available that you can use anywhere, from your applications to your CLIs.

Other than that there are more than 18,000 CLIs on the npmjs repository. So with these figures, you will probably get the idea that the JavaScript community is huge. Whatever you are going to build, people are eventually going to use it.

Wrapping Up

There are many other reasons why you should use JavaScript to build such CLIs other than these two. So I would highly recommend you to take a look and learn to build these awesome dev tools with JavaScript.

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