This is a two article series on Node.js Process Arguments. You can find these two articles below:
In part 1, I talked about how you can get arguments from the terminal through the process.argv
array. It still provides you with two elements in the array even if you don't provide any argument. The first element is the execution path of Node.js and the second one is the path of the file that is being executed.
Now let's take a look at how you can use this array in your CLI to set up flags.
Since we know that the first two elements of this array are always going to be occupied, so let's slice it from the third index. We can do that with the following code:
process.argv.slice(2)
Let's add a no social flag to my name CLI. With this flag, if the user types --no-social
along with the awais
command then social information will not be printed out.
Now I am going to create a variable and save all the social information inside it. I am going to check now if the arguments array has a --no-social
flag or not. If it does then my CLI will not print from the variable I just created.
Let's take a look at the code:
const args = process.argv.slice(2);const socialInfo = `${twitterClr(` Twitter `)} ${dim(`https://twitter.com/MrAhmadAwais`}}${githubClr(` GitHub `)} ${dim(`https://github.com/ahmadawais`}}${purple(` Blog `)} ${dim(`https://ahmadawais.com/`}}`const printSocial = args.indexOf(`--no-social`) === -1;const social = printSocial ? socialInfo : ``;
Now after this code, I just have to replace where I had put my social info in the CLI with the following piece of code:
${social}
The next thing I am going to do is to run the CLI with the following command:
awais --no-social
This is the output I received. You can see that there is no social information printed out in the terminal now.
This is how you can use process object argv array to set flags in your CLI. Now go ahead and try it out in your CLI!