How to create a basic cli app using node and prompts

How to create a basic cli app using node and prompts

###What is a command-line interface(CLI) ?

It’s just a program that takes command line arguments and performs a task.

###Why you should build your CLI in JS using node?

Well, there are a lot of npm packages that provide advanced functionality and you’ll probably don’t have that much time to build a particular functionality from scratch.

With that beeing said, let’s get started.

First, what will our CLI tool do? It should prompt us the following: Type your name [“x” for exit] Then it should wait for our input and loop again.

###Let’s get started: 1. We need to create a package file using npm init: npm init
2. There is a package that can help us retrive input from command line npm install prompts
3. Code Will start by adding the required package that we just installed at point 2:

const prompts = require('prompts');
Then will move to our function which will handle all the necessary code:

async function loop() {

This function must be declared async because we are going to make use of await, therefor our function must be perceded by async keyword.

Loop function code:
let input = {};

while(1) {
	input = prompts({
		message: 'Type your name ["x" for exit]\n',
		type: 'text',
		name: 'value'
		const { value = 'x' } = await input;

	if(value.toLowerCase() === 'x') {
	if (value) {
		console.log(`Hello ${value}!`);
	}else {
		console.log('Please enter your name!');


As you see we are using the prompts package to present the user with the input Type your name [“x” for exit]

Then we are going to wait until the user hits enter and our promise gets resolved.
const { value = 'x' } = await input;
After this point we are just going to output the name and our message on the screen and loop again.

At the end you’ll se that we have process.exit(0), this is because every program that is terminated correctly should have an exit code 0

That’s it, Hope you enjoyed it !

Related Posts