Skip to main content

Introduction to Node.js - Part-1 Node Command line Interface(CLI) App

Aim

This document is get to start with the Node.Js. This is a simple introduction to Node and Its corresponding frameworks. This will help you to create a simple chit chat server application using node.js, express.js and socket.io. I have used the chat demo app of socket.io to learn you node.

Introduction to Node.Js CLI


Introduction to Node

If you are from the Java and .net background. You might have create several JSP and ASP application to learn Java and ASP web framework. While create web app. You also learned JavaScript to interact with the HTML dom elements. If you go to the wikipedia definition of node which is “Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux, FreeBSD, and IBM_i”.


It tells that Node is a framework where you can write code in Javascript programming language on server side and you can run your application on Node anywhere in all known OS.
Yes you heard right, You can write server side programming in java script.
Node has did something awesome with Google v8 and libuv. Node created a layer of awesomeness where you can write code on simple javascript and perform most of the I/O operation. Awesomeness of node did not ends here. All these I/O operation you can perform asynchronously. I guess you have heard about callback. In Javascript you can pass function as argument. Its mean when you do some async work you pass the callback which will run when async task has completed.
Simple code to read a file:
fs.readfile(fileName || 'file1.txt', callback ); // complete path of the filename
Here callback can be any large function. Where you can write you own Logic to perform some action when read file has completed.
Lets Start with Node.Js :-)

Installation and Setup

Installation of node is very easy. You can download binary from the official node.js website.

Window

Download Windows installer(.msi) according to your computer processor’s architecture. You will get something like node-v0.10.35-x64.msi. Just double click on it to install it. Just follow the instruction. Once it finished, open your command prompt type below given command to check whether node has been properly installed or not.
c:\Users\Deepak> node
v0.10.35
c:\Users\Deepak> node
1.4.28


Linux

Download Linux Binary(.tar.gz) according to your computer processor’s architecture. You will get something like node-v0.10.35.tar.gz. Extract the tar in a folder and set the path to the bin folder. Once you are done, check whether node has been properly installed or not.
Extract and create soft link
   $ cd /opt/
   $ tar xvz node-v0.10.35-linux-x64.tar.gz
   $ chwon ur_user_name:ur_user_name node-v0.10.35-linux-x64
   $ ln -s node node-v0.10.35-linux-x64
Check for node and npm
   $ node -v
   $ npm -v
Introduction to node REPL/shell
Node is a complete package. it provides you node shell where you can run and test your node program very easy. To launch Node shell Open your command prompt and type node press enter. It will take you to node shell. Write you first node program on node shell.
   $ node
   > console.log(‘Hello From Node Shell, Its awesome.’);
You will get output as Hello From Node Shell, Its awesome.
Here console is an object provided by the Node. You can use it to print something synchronously on stdout and stderr.
Hello from javascript
As i already mention, Node is a platform where you can write code in javascript and run it. Here is your first node program. Create a javascript file(suppose Hello.js here) using your favorite browser. Write something creepy in node manner in it and run it.
//Hello.js
var message = 'something creepy going to happen ;)'
console.log(message);

   $ node Hello.js

Talking Tom
Lets create a simple node cli app, Talking Tom. We will use redline module of the node.
Recipe:
Step-1: Add some creepy word at the start of the program. So that its look cool :-D
//Talking_Tom.js
var message = 'something creepy going to happen ;)'
console.log(message);
Step-2: Require the ‘readline’ node module
var readline = require('readline');
Step-3: Create an interface for the input and output stream.
var rl = readline.createInterface(process.stdin, process.stdout);
Step-4: Set the prompt in your style
rl.setPrompt('$ my_style >');
Step-5: Call the prompt for the first time. what it will do. it will create a prompt to your cli. where you can write something. it will stream in stdin which you can use for further process.
rl.prompt();
Step-6: Track the line by using line event. This will track your input to the prompt. Whenever you will enter ‘\n’ as input in prompt. The line event will fire and callback the function you have assign to the ‘line event’.
rl.on('line', function (line) {
  var lowerLine = line.trim().toLowerCase();
  var thisEndOfTheWorld = 'EXIT', itsQuestion = 'QUESTION', itsAnAnswer = 'ANSWER';
  var myMessageType = itsAnAnswer;
  if (lowerLine == 'bye') {
      myMessageType = thisEndOfTheWorld;
  }
  else if (lowerLine.indexOf('?') > -1) {
      myMessageType = itsQuestion;
  }
  else {
      myMessageType = itsAnAnswer;
  }
  switch (myMessageType) {
      case thisEndOfTheWorld:
            console.log('This is the end of the world.. :/ Have a great day!');
  break
      case itsQuestion :
          //ask same question
          console.log(line);
          break;
      case itsAnAnswer :
          //give same answer which is My name is Tom n I love cookies
          console.log('My name is Tom n I love cookies');
          break;
      default:
          console.log('Something fishy happend.. :/');
          break;
  }
  rl.prompt();
});
We have done really creepy thing in last few line :-D. We have checked for the input. If user has entered ‘bye’. We have reply back with end message. If it is not the end of the world than we check whether its a question. If it is a question ask same question otherwise give an honest answer :-D
If you run the program, you will see that program will never terminates. Now we will attach the close event on readline interface and emits it on the end of the world.
Step-7: Add ‘close event’ and exit the program on the end of the world
case thisEndOfTheWorld:
            console.log('This is the end of the world.. :/ Have a great day!');
   rl.close()
          break
 }
  rl.prompt();
})
rl.on('close', function () {
  console.log('This is the end of the world.. :/ Have a great day!');
  process.exit(0);
});
Final code will be something like:
////Talking_Tom.js
var message = 'something creepy going to happen ;)'
console.log(message);


var readline = require('readline'),
  rl = readline.createInterface(process.stdin, process.stdout);


rl.setPrompt('$ my_style >');
rl.prompt();
rl.on('line', function (line) {
  var lowerLine = line.trim().toLowerCase();
  var thisEndOfTheWorld = 'EXIT', itsQuestion = 'QUESTION', itsAnAnswer = 'ANSWER';
  var myMessageType = itsAnAnswer;
  if (lowerLine == 'bye') {
      myMessageType = thisEndOfTheWorld;
  }
  else if (lowerLine.indexOf('?') > -1) {
      myMessageType = itsQuestion;
  }
  else {
      myMessageType = itsAnAnswer;
  }


  switch (myMessageType) {
      case thisEndOfTheWorld:
          rl.close()
          break
      case itsQuestion :
          //ask same question
          console.log(line);
          break;
      case itsAnAnswer :
          //give same answer which is My name is Tom n I love cookies
          console.log('My name is Tom n I love cookies');
          break;
      default:
          console.log('Something fishy happened.. :/');
          break;
  }
  rl.prompt();
})
rl.on('close', function () {
  console.log('This is the end of the world.. :/ Have a great day!');
  process.exit(0);
});

Run the code:

   $ node Hello.js

continue...

Comments

  1. nice blog to get an overview of node.js...... keep writing such great blogs in future as well.

    ReplyDelete
  2. Nice blog I learn a lot Thanks

    ReplyDelete
    Replies
    1. Thnks..working on next draft..upload it soon :)

      Delete
  3. Thanks for the wonderful article, Please continue.

    http://www.drtuts.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Loading- Exporting Modules in Node.Js

Loading a module: In node you can load module either using the path to the module or giving name  of the module. require keyword is used to load  module in node. Its look for the file in given path to load module if the require module is not core node module. You can install third party module using NPM (Node Package Manger). It downloads from the global repository to your local machine. var module = require( 'module-name' ); The require function returns an object that represent the module which have exported. It can be any javascript data type. It could be function, an array, any javascript object. Exporting a module: The CommonJs Module system is use to share the object or properties in node.js. Since Javaascript runs program in global scope. CommonJs Module is one of the best way for creating and sharing namespace in the javascript environment. Here below given an example to export a function in node.js. //person.js /** * Created by deepak.m.shrma@gm

Provide SSL support over your http NodeJs-Express API

A simple HTTPS server using node.js: Using ExpressJS and openssl, you can easily provide SSL support to your Api. For that you have to follow below given steps. Steps to create a https server. Generate an SSL certificate with that key Create a app.js file Install express module Run to Test your app. :-) Generate an SSL certificate with that key: For development purposes you can create a self-certified certificate. First, generate a private key on linux-based system. It will store a 1024 bit RSA key in the file key.pem openssl genrsa 1024 > key.pem Then, generate an SSL certificate with that key: openssl req -x509 -new -key key.pem > key-cert.pem Create a app.js file var fs = require("fs"),                 //Requires fs module to read key, cert files     express = require('express'),       // call express     app = express(),                     // define our app using express     http = require("http"),