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.
==> Download it using npm install speedtestcli -g and test internet speed on your terminal.
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.
If you save the code and run it via Node using.
You will be able to see the output in console. But this is not what we want. We want our input go like this.
And it should print
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.
"sayHello": "cli.js"
}
This line tells Node to execute particular file on this command. So its syntax is.
"your-command" : "file-to-execute"
}
We need to modify cli.js to following.
Save the code and run it using following command.
It will print
On screen.
To make it command line you need to add following in start of the main script.
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.
console.log("Hello",process.argv[2]);
Now run following command to install it in your system as a command line application.
This is it. Once it is installed you can access it using following command on terminal.
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.
Here is my 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.
For ease, i select speedtest as command. You can change it as per your preference. Let’s write some code for main file.
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
Install it in your system using.
And run your specified command in above case speedtest on terminal to see output.
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.