Codementor Events

Building CLI Apps with Nodejs without any framework

Published Dec 24, 2018

Go to the profile of ashay mandwarya

ashay mandwaryaBlockedUnblockFollowFollowing

Nov 20


Photo by Chris Ried on Unsplash

Command Lines(CLI) or Terminals are the most basic ways to communicate with a OS. It was the only way to interact with a computer in older times as there was no GUI at that time. Even after having beautiful GUI’s nowadays Terminals are still widely used as they provide to the point information without any distractions and also helps do many tasks which simply can’t be accomplished by using the GUI and is also fast.

CLI based apps can be created in all sorts of languages that support running on Terminals. We will be using Nodejs as it is becoming widely popular.

We will be making a weather app called Seasons which will show the weather of your current location or the location you enter. This tutorial will show minimal of the output but it is quite versatile and can be expanded easily.

Before we start make sure you have Node installed on your system.

Project Structure=>

Seasons
      |___bin
          |___index.js
      |___lib
          |___seasons.js

The above will be the project structure we will be using for the project.

To start the project we first need a package.json which tells about the version of the project, author, licence etc.

Use for starting right away with defaults for package.json

npm init -y

Or

npm init //for entering the details

Now, open seasons.js.

const color=require('colors');

const request=require('request');

exports.seasons= function(code)

{

let apiKey = 'xxxxxxxxx';

let city = code;

let url = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid='+apiKey;

var uri='http://ip-api.com/json';

if(code)

{

request(url,function(err,response,body){

if(err)

{

return JSON.parse(error);

}

else{

console.log('****'+color.blue(JSON.parse(body).name) +'--'+ color.green(JSON.parse(body).weather[0].main) +'--'+ color.grey(JSON.parse(body).weather[1].description) +'--'+ color.cyan(JSON.parse(body).main.temp)+'--'+ color.red(JSON.parse(body).main.temp_min) +'--'+ color.yellow(JSON.parse(body).main.temp_max)+'****');

}

});

}

else

{

request(uri, function(err,response,body){

if(err)

{

console.log('error');

}

else{

var cit=JSON.parse(body);

var ura='http://api.openweathermap.org/data/2.5/weather?q='+cit.city+'&appid='+apiKey;

return request(ura,function(err,response,body){

if(err)

{

console.log('error')

}

else

{

console.log('****'+color.blue(JSON.parse(body).name) +'--'+ color.green(JSON.parse(body).weather[0].main) +'--'+ color.grey(JSON.parse(body).weather[0].description) +'--'+ color.cyan(JSON.parse(body).main.temp)+'--'+ color.red(JSON.parse(body).main.temp_min) +'--'+ color.yellow(JSON.parse(body).main.temp_max)+'****');

}

});

}

});

}

}

The above code is self explanatory. There are 2 API used in the code.

One is used to make a GET request to ip-api.comto get exact location via IP and sending the location retrieved to the weather API.

Weather API makes a POST request sending the location and retrieving the weather information from openweathermap.org.

#Note- All ajax request used here are exchanging data in JSON format.

The rest of the code queries the JSON and logs the required details. You can display as much as you want but this tutorial shows only the temperature.


#!/usr/bin/env node

const colors=require('colors');

const outside=require("../lib/outside");

var arguments=process.argv.splice(2);

var city=null;

if(arguments[0]=='--loc')

{
city=arguments[1];

outside.outside(city);
}

else if(arguments[0]=='--help' || arguments[0]=='-h')

{

console.log("@@@@@@@@@@Welcome@@@@@@@@@@@@@")

console.log("-h or --help for help");

console.log("--loc followed by the location for weather data");

console.log("outside with no arguments gives current location weather")

console.log("--abt tells about the app and author")

console.log("Legend===>> **** City Name--weather condition--weather description--temperature--min temperature--max temperature");

}

else if(arguments[0]==null)

{

(outside.outside());

}

else if(arguments[0]=='--abt')

{

console.log(colors.america('Outside is a simple command line application which shows the days weather forecast'));

console.log(colors.green('Author: Ashay Mandwarya'));

console.log(colors.rainbow('Thanks to openweathermap.com and ip-api.com for their api support'))

console.log(colors.bgMagenta('Thanks to the developers of colors for such a great library'));

}

Start the code with a shebang. It basically tells the system this isn’t a shell script and it should use a different interpreter.

process.argv[] is an array that stores all the process running with the application. We can slice the first 2 elements from the array as we do not require them. The 3rd element is the argument in the query. With a simple loop we can define functionality of each and every argument and make an interactive application to provide with the most data without creating a clutter.

Different attributes( — attributes) can be defined and used as per the requirement of the application and the functionality can be defined accordingly.

You can also create a helper and an about argument to add more dimension to the application.

Our application is almost completed.

Last step → Open package.json file and enter the following line

{

"name": "seasons",

"version": "1.0.0",

"description": "Seasons CLI weather app",

"main": "index.js",

"directories": {

"lib": "lib"

},

"bin": {

"seasons": "./bin/index.js"

},

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"keywords": ["weather","cli","node"],

"author": "Ashay Mandwarya",

"license": "ISC",

"dependencies": {

"colors": "^1.3.2",

"request": "^2.88.0"

}

}

This tells the command line which file to run when the defined command is entered.


To make the seasons key word global i your system you need to enter a simple line.

npm link

This line of codes creates a symlink (Symbolic Link) between the code and makes it global, means we can run the command from any terminal in our system.

This is the most basic and simple type of a CLI app. With the help of external libraries much complex apps can be created. You can also publish your app to npm by using

npm publish

It will first ask to login, enter the credentials and then publish.

Hope you liked my tutorial and keep developing.

Discover and read more posts from Ashay Mandwarya
get started