Develop command line application using NodeJS

Node.js provides utilities to develop command line application. There are some cool application like express-geenrator and nodemon which runs on command line.

In this tutorial we will learn how to use command line utilities in Node and develop sample internet speed test program using speedtest.net API.

speedtest command line app
npm install speedtestcli -g

==> Download it using npm install speedtestcli -g and test internet speed on your terminal.

DOWNLOAD

Basic Hello %Your Name% Command line App.

This example will take your name as input and gives you output right in console with greeting. Let’s first write a code to print “Hello World” in code.

cli.js
console.log("Hello World");

If you save the code and run it via Node using.

node cli.js

You will be able to see the output in console. But this is not what we want. We want our input go like this.

node cli.js Shahid

And it should print

Hello Shahid

Let’s develop this. First create package.json using npm init command OR you can copy this.

{
  "name": "HelloWorld",
  "version": "1.0.0",
  "description": "",
  "author": "",
  "license": "ISC",
  "bin": {
    "sayHello": "cli.js"
  },
  "dependencies": {}
}

Did you notice this line.

  "bin": {
    "sayHello": "cli.js"
  }

This line tells Node to execute particular file on this command. So its syntax is.

"bin" : {
   "your-command" : "file-to-execute"
}

We need to modify cli.js to following.

cli.js
console.log("Hello",process.argv[2]);

Save the code and run it using following command.

node cli.js Shahid

It will print

Hello Shahid

On screen.

To make it command line you need to add following in start of the main script.

#!/usr/bin/env node

Above line tell the System that the script should be executed with the first executable named node that’s found in your current PATH. /bin/env is standard Unix utility that looks at your current environment.
So final code should be like this.

cli.js
#!/usr/bin/env node
console.log("Hello",process.argv[2]);

Now run following command to install it in your system as a command line application.

npm install -g

This is it. Once it is installed you can access it using following command on terminal.

sayHello Shahid

Developing Speedtest command line app.

We all know and use speedtest.net frequently to check Download and upload speed. They do provide web services too for external integration of speedtest features.

There is node module which wraps the API provided by speedtest.net ( Thanks to @ddsol for this ) called speedtest-net. We will be using that to develop our command line application.

Let’s begin with Package.json file. Use npm init to Generate package.json for your application ( It’s a good practice ). You may specify dependencies in the wizard or hit enter to get package.json with basic information.

You can install dependencies using.

npm install chalk progress speedtest-net --save

Here is my package.json.

package.json
{
  "name": "speedTestCLI",
  "version": "1.0.0",
  "description": "",
  "author": "",
  "license": "ISC",
  "bin": {
    "speedtest": "index.js"
  },
  "dependencies": {
    "chalk": "^1.1.1",
    "progress": "^1.1.8",
    "speedtest-net": "^1.0.3"
  }
}

Install dependencies by using following command if you have not done already.

npm install

For ease, i select speedtest as command. You can change it as per your preference. Let’s write some code for main file.

index.js
#!/usr/bin/env node
var speedTest    =  require('speedtest-net');
var ProgressBar  =  require('progress');
var chalk        =  require("chalk");

var test = speedTest({maxTime:5000});

var bar,pingTime;

// Event triggered when best Server is found.

test.on('testserver',function(server) {
    pingTime = server.bestPing;
});

// Invoke every time when download speed check begin
// Return completion value in percentage

test.on('downloadprogress',function(pct){
    prog('Checking Download Speed ',pct);
});

// Invoke every time when upload speed check begin
// Return completion value in percentage

test.on('uploadprogress',function(pct){
    prog('Checking Upload Speed ',pct);
});

// Invoke When final data recieved

test.on('data',function(data){
    console.log(chalk.cyan("Ping : "),Math.abs(pingTime),chalk.dim('ms'));
    console.log(chalk.cyan("Download Speed : ") + data.speeds.download + chalk.dim(" MBps"));
    console.log(chalk.cyan("Upload Speed : ") + data.speeds.upload + chalk.dim(" MBps"));
});

// in case of error, exit.

test.on('error',function(error){
    process.exit(1);
});

/*
    function : prog
    params : type and percentage.
    task : update the progress bar.
*/


function prog(what,pct){
    // if its completed, terminate current progress.
    if (pct>=100){
        if (bar) bar.terminate();
        bar=null;
        return;
    }
    // if bar object is not created
    if (!bar) {
        var green = 'u001b[42m u001b[0m',
              red = 'u001b[41m u001b[0m';
        bar = new ProgressBar(' '+what+' [:bar] :percent', {
            complete: green,
            incomplete: red,
            clear: true,
            width:40,
            total: 100
        });
    }
    // else update the bar with coming value.
    bar.update(pct/100);
}

Run the program using

node index.js

Install it in your system using.

npm install -g

And run your specified command in above case speedtest on terminal to see output.

speedtest command line app
npm install speedtestcli -g

Conclusion:

We learned how to develop a real-time command line application using Node.js. If you are developing framework OR working with any boilerplate generator application then command line utilities are very useful to you.

Further reading:

Commander – NPM module designed for simple command line application solution.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126