LEARNNode CLI Automation

Node Module Naming – Part #5

This is a six articles series for building and publishing a node module from scratch. You can find all these articles below:

I have one other thing that I want to add to this cli-alerts node module before publishing it. And that is to allow the user to add some other string in place of the message type. So without any further ado, I am going to implement this feature in this article.

Adding the Name Key

I can easily implement the feature I described above by using a ternary operator and with JavaScript template literals. The code of it will look something like this:

/**
* CLI Alerts
*
* Cross Platform CLI Alerts with colors
* Works on macOS, Linux, Windows.
* Alerts: `success`, `info`, `warning`, `error`.
*
* @author Awais <https://twitter.com/MrAhmadAwais/>
*/
const chalk = require('chalk');
const sym = require('log-symbols');
const green = chalk.green;
const greenI = chalk.green.inverse;
const red = chalk.red;
const redI = chalk.red.bold.inverse;
const orange = chalk.keyword('orange');
const orangeI = chalk.keyword('orange').inverse;
const blue = chalk.blue;
const blueI = chalk.blue.inverse;
module.exports = options => {
const defaultOptions = {
type: `error`,
msg: `You forgot to define all options.`,
};
const opts = { ...defaultOptions, ...options };
const { type, msg, name } = opts;
const printName = name ? name : type.toUpperCase();
if (type === `success`) {
console.log(`\n${sym.success} ${greenI(` ${printName} `)} ${green(msg)}\n`);
}
if (type === `warning`) {
console.log(`\n${sym.warning} ${orangeI(` ${printName} `)} ${orange(msg)}\n`);
}
if (type === `info`) {
console.log(`\n${sym.info} ${blueI(` ${printName} `)} ${blue(msg)}\n`);
}
if (type === `error`) {
console.log(`\n${sym.error} ${redI(` ${printName} `)} ${red(msg)}\n`);
}
};

So what's happening is if the user is providing a name key to the object that our node module will take then it will be used in place of the message type. Otherwise, the default behavior will work.

I am going to open my test.js file. I am going to provide a name key with a value of All done! and when I test it with npm test, it's going to look something like this:

name key works

As you can see that instead of SUCCESS, DONE is printed on the console.

Wrapping Up

I have added the final feature I wanted in my cli-alerts node module. I also tested it to make sure it is working. And that is it. Now I am going to publish it on npmjs.

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