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
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);
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.
…
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
nice blog to get an overview of node.js...... keep writing such great blogs in future as well.
ReplyDeleteThanks buddy.. :-) i will try my best..
DeleteNice blog I learn a lot Thanks
ReplyDeleteThnks..working on next draft..upload it soon :)
DeleteThanks for the wonderful article, Please continue.
ReplyDeletehttp://www.drtuts.com