UNDERSTANDING NODE.JS BY BUILDING COMMAND LINE APPS

UNDERSTANDING NODE.JS BY BUILDING COMMAND LINE APPS

<strong>Originally published by Chimezie Enyinnaya </strong><em>at&nbsp;</em><a href="https://pusher.com/tutorials/node-command-line-app" target="_blank">pusher.com</a>

In this tutorial, I’ll be showing how to build command line applications using Node.js.

JavaScript is very popular for building all kinds of applications, from frontend applications to backend and mobile applications. The language keeps evolving and now you can build command line applications or control hardware devices like drones with JavaScript.

Prerequisites

This tutorial assumes the following:

  • Node.js and NPM installed on your computer
  • Basic knowledge of JavaScript and Node.js
What we’ll be building

In this tutorial, we’ll be learning how to build simple command line application. We’ll be building a command line weather application using Node.js. With our command line weather application, we’ll be able to get the current weather in any city in the world. We’ll also be able to get a forecast for any specified city using a different command line parameters.

Getting started

Let’s start by setting up our project and installing dependencies:

    $ mkdir weatherCLI
    $ cd weatherCLI
    $ npm init -y

This will create an empty directory called weatherCLI that will hold all our project files. After our project directory has been created, we change the directory to the project directory and initialize our project. A package.json file will be created and now we can proceed to install our project dependencies:

    $ npm install commander node-fetch --save

Commander is a Node.js library that makes writing command line applications easy. We’ll be leveraging the library to build our command line application. node-fetch is also a light-weight module that allows us make requests to external services to fetch data. We’ll use it to fetch weather data from APIXU.

Obtaining API keys

To obtain our API keys, we need an account on APIXU. Once you’ve created an account, login to the dashboard to find your API key that looks like 4a8****3e``*e248ac1*****``04.

Building the command line app

First, let’s create our project files. Create a src directory, and within it, create two files:

    $ touch src/index.js src/commands.js

Once the files are created, we’ll go ahead to create our commands for the app by adding the code below inside src/commands.js:

    // src/commands.js

    const fetch = require("node-fetch");
    const APIXU_KEY = "<YOUR APIXU KEY>";

We import the node-fetch library, then we create an APIXU_KEY variable, which holds our API key.

Next, we’ll go ahead to create two functions: fetchNow() to fetch the current weather for any specified city and weatherForecast() to fetch the forecast of any specified city likewise:

    // src/commands.js

    const fetchNow = async (city) => {
      const response = await fetch(`https://api.apixu.com/v1/current.json?key=${APIXU_KEY}&q=${city}`);
      const data = await response.json();

      const now = {
        location: data.location.name,
        country: data.location.country,
        longitude: data.location.lon,
        latitude: data.location.lat,
        temparature: data.current.temp_c,
        condition: data.current.condition.text
      }

      console.log(now)
    };   

The fetchNow function is an asynchronous function that will return a Promise. It takes the passed cityas a parameter in order to make the complete API request. The await operator can only be used inside an asynchronous function and it returns the fulfilled value of the Promise, or the value itself if it's not a Promise.

The now object holds just the necessary information we need from the data returned from the API request. The same thing applies to the weatherForecast function:

    // src/commands.js

    const weatherForecast = async (city) => {
        const response = await fetch(`https://api.apixu.com/v1/forecast.json?key=${APIXU_KEY}&q=${city}`);

      const data = await response.json();

      console.log(data.forecast)
    };

After defining all functions, we need to export them so they can be used in our command line program:

    // src/commands.js

    module.exports = {
      fetchNow,
      weatherForecast
    };

Our main application file src/index.js will hold the main application logic. Add the code below inside src/index.js:

    // src/index.js

    const program = require('commander');
    const { fetchNow, weatherForecast } = require('./commands');

We import the commander library and also the defined functions from src/commands.js. After the dependencies have been imported, we’ll define our program parameters:

    // src/index.js

    program
      .version('0.0.1')
      .description('Command line Weather Application')

    program
      .command("now <city>")
      .alias('n')
      .description('see the current weather in the specified city')
      .action(city => fetchNow(city));

    program
      .command("forecast <city>")
      .alias('f')
      .description('see the weather forcast of a specified city')
      .action(city => weatherForecast(city)); 

Let’s go over what each piece of the code above does:

  • .version allows us define the current version of our command line application
  • .command defines how the parameter should be passed to the program with any extra arguments
  • .alias defines an alternative short form parameter that can be passed to the program instead of typing a longer one.
  • .description is the description of the alias
  • .action will call whatever function is passed to it. The action runs the functions and displays whatever is returned from the function. The action is also responsible for handling interactions with the user if the command line application is an interactive application.

In order to read all parameters and arguments passed to our program, we have to parse the inputs after the program command. Add the snippet below as the last line inside weatherCLI.js:

    // src/index.js

    program.parse(process.argv)

Running and testing the CLI application

To run and test our application, run the command below:

    $ node src/index.js now lagos

It will return the current weather in Lagos as in the image below:

To fetch the weather forecast for Lagos, run:

    $ node src/index.js f lagos

Also, we can run additional commands as below:

    $ node src/index.js --help

This will return the application usage menu.

    $ node src/index.js --version

This will return the application version as specified earlier in src/index.js.

Conclusion

From the tutorial, we can see how easy it is to create command line applications using the Node.js Commander library. We’ve been able to create a command line application that can display the current weather of any city in the world using the APIXU. You can work more on the display formats so the displayed data looks interesting to users and also add a network loader while the application is fetching the weather reports.

The complete code for this tutorial is available on GitHub.

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Difference between AngularJS, React, Ember, Backbone, and Node.js.

The most common thing between all of them is that they are Single Page Apps. The SPA is a single page where much of the information remains the same and only some piece of data gets modified when you click on other categories/option.

Node.js Tutorial for Beginners | Node.js Crash Course | Node.js Certification Training

This courseis designed for professionals who aspire to be application developers and gain expertise in building real-time, highly-scalable applications in Node.js. The following professionals can go for this course :

Why learn Node.js?

Node.js uses JavaScript - a language known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Using Node.js you can build simple Command Line programs or complex enterprise level web applications with equal ease. Node.js is an event-driven, server-side, asynchronous development platform with lightning speed execution. Node.js helps you to code the most complex functionalities in just a few lines of code...

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Docker for Node.js Projects From a Docker Captain

Intro To MySQL With Node.js - Learn To Use MySQL with Node!

Node.js Absolute Beginners Guide - Learn Node From Scratch

React Node FullStack - Social Network from Scratch to Deploy

Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

Complete Next.js with React & Node - Beautiful Portfolio App

Build a Blockchain & Cryptocurrency | Full-Stack Edition