Node.js: Command line programming
This article is part of our Academy Course titled Building web apps with Node.js.
In this course, you will get introduced to Node.js. You will learn how to install, configure and run the server and how to load various modules.
Additionally, you will build a sample application from scratch and also get your hands dirty with Node.js command line programming.
Check it out here!
Table Of Contents
1. Introduction
Node.js is one of the most hyped technologies over the past few year. It is built with JavaScript and runs on the Chrome V8 engine Runtime.
Node.js offers the following features while developing Applications:
- Develop once, run everywhere, from command line, server, or the browser.
- Event-driven programming.
- Non-blocking Input-Output Model.
- The main event loop from Node.js runs in Single thread.
In this article, we will discuss about node.js command line programming. We will create a sample program which processes any file and interacts with users.
2. Utility Programs with Node.js
Some useful modules are available with node.js, such as:
- Processing some data and preparing reports with node.js.
- Getting twitter data and storing them in the repository for further processing.
So, first let’s build a simple program on to show you how to process command line arguments in node.js
Our Program listing is nodecmd.js.
nodecmd.js:
process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });
Once we run this program with:
node nodecmd.js one two three
we will have the output as follows:
0: node 1: /nodeapps/nodecommandline/nodecmd.js 2: one 3: two 4: three
Here, the first printing line is node – the program. Second one is the program file name. The other three lines are printouts of the arguments.
process
is a core module that comes with the node.js installation. More documentation on process
can be found here.
We will use a new module, named commander.js
, for the command line processing in node.js> It has several useful options which we will look here.
First, in order to install commander.js, we issue the following command in the node.js console:
npm install commander
Below is the listing for the sample command line program:
nodecommand.js:
var program = require('commander'); program .version('0.0.1') program .command('show [name]') .description('initialize command') .action(function(name){ console.log('Yes '+ name +'...I have started...'); }); program .command('bye') .description('by command') .action(function(){ console.log('Bye for now'); }); program .command('*') .action(function(env){ console.log('Please enter a Valid command'); }); program.parse(process.argv);
Now, some commands that we can run in the node.js console are:
1.
node nodecommand.js -V
It will show the version number for the program, which we have defined with
program .version('0.0.1')
2.
node nodecommand.js -h
It will show a utility console with all the commands and usages like:
- Usage: nodecommand.js [options] [command]
- Commands:
- show [name]: initialize command
- bye: by command
- *
- Options:
- -h, –help: output usage information
- -V, –version: output the version number
3.
node nodecommand.js show Piyas
It will output the following in the console:
Yes Piyas...I have started...
Here Piyas
is passed as an argument in the nodecommand.js program.
More on the use of commander can be found here.
Now we can also run the program without prior initialization with the node command.
We can save the above program content with the follwing line in the upper section of the code and save the file as nodesamplecommand:
#!/usr/bin/env node
Now if we run the statements:
./nodesamplecommand -h
or
./nodesamplecommand show Piyas
they will give the same output as the previous program.
The only thing we have to make sure is to have the program node
in the system environment path.
3. Command Line and User Interaction
Let’s continue with a simple user interaction program with the node process
as below:
nodeuserinteraction:
#!/usr/bin/env node process.stdin.resume(); process.stdin.setEncoding('utf8'); var util = require('util'); process.stdin.on('data', function (text) { console.log('received data:', util.inspect(text)); if (text === 'exit\\n') { complete(); } else { invalidCommand(); } }); function complete() { console.log('There is nothing to do now.'); process.exit(); } function invalidCommand() { console.log('Please enter the valid command'); }
In the execution of the program above, the process
module will resume in the node.js console till some user input arrives. As long as the user enters some data except exit
, the program will prompt as follows:
Please enter the valid command
The program will stop when we issue the exit
command.
4. File Handling in Node.js Command Line Program
Now we will work with a sample program, which will work with files. The user will enter a file as input in the console. The program will extract the keywords from the file and write the words in a different file.
To get the keywords from the file, we will use module ‘keyword-extractor’:
npm install keyword-extractor
This will install the keywords extractor library in the local repository.
Now the program listing of noderemovestopwords
:
#!/usr/bin/env node // Node environment path in Linux var keyword_extractor = require("keyword-extractor"); fs = require('fs'); var program = require('commander'); program .version('0.0.1') program .command('process [filename]') .description('initialize command') .action(function(filename){ console.log(filename); fs.readFile(fs.realpathSync(filename), 'utf8', function (err,data) { if (err) { return console.log(err); } //Keyword Extraction var extraction_result = keyword_extractor.extract(data,{ language:"english", return_changed_case:true }); fs.writeFile(filename+'.out.txt', extraction_result, function (err) { if (err) return console.log(err); console.log('File writing done'); }); }); }); program.parse(process.argv);
To run the program, we need to write:
./noderemovestopwords process <>
which will output a file named <<File Name>>.out.txt
in the output directory.
Let’s now discuss the program:
- First we have taken the argument as
filename
in Command line. - After this, we have read the file and processed the file contents using the keyword extraction library. As this keyword extraction process is a synchronous process, we have written the extracted content to a different file with the Node.js filesystem
writeFile
methods. - And finally we have logged a message when the process ends within the
writeFile
callback function.
So this is an example of file handling through node.js command line program.
5. Publish the Program to NPM
NPM makes it really easy to share Node.js programs to the world. The Steps are:
- Create a configuration file for program.
- Execute the command publish.
There should be a package.json file for the configuration:
{ "author": "Piyas De", "name": "noderemovestopwords", "url" : "http://www.phloxblog.in", "description": "A sample CLi program created to extract the keywords from a given file and output the keywords to a different file", "version": "0.0.4", "repository": { "type": "git", "url": "https://github.com/piyasde/nodecommandline" }, "main": "./bin/noderemovestopwords", "keywords": [ "keyword", "extractor", "commandline" ], "bin": { "noderemovestopwords": "./bin/noderemovestopwords" }, "dependencies": { "commander": "2.1.x", "keyword-extractor": "0.0.7" }, "engine": "node >= 0.10.22", "license": "BSD" }
A Note for the Folder Structure:
nodecommandline |--src |--bin | |--noderemovestopwords |--package.json |--README.md
Now we need to execute:
npm adduser
: to add the user name for whom the node.js package is uploaded.npm publish
: to publish the node.js package to the Repository.
6. Download the Source Code
In this tutorial we discussed command line programming in Node.js. You may download the source code here: Nodejs-Command_line.zip