You are on page 1of 8

Node.

js Introduction
Node.js is a platform for writing network and web applications.
Node.js is built around an event-driven nonblocking model of programming.
Running Node.js and "Hello World!"
Create a file called hello.js:

/**
* comment.
*/
console.log("Hello World!");

Now, we can execute this file from the command line with
node hello.js

And you should see this output:


Hello World!

Variables
Variables are defined in JavaScript using the var keyword.
For example, the following code segment creates a variable foo and logs it to
the console.

var myData = 123;


console.log(myData);

The code above generates the following result.

The JavaScript runtime has the opportunity to define a few global variables
that we can use in our code.
One of them is the console object.
The console object contains a member function (log), which takes any number
of arguments and prints them to the console.

First Web Server


Enter and save the following into a file called web.js :

var http = require("http");


/*from www .j a v a2 s. com*/
function process_request(req, res) {
var body = 'Thanks for calling!\n';
var content_length = body.length ;
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain'
});
res.end(body);
}
var s = http.createServer(process_request);
s.listen(8080);

To run it, simply type


node web.js

Your computer now has a web server running on port 8080.


We can type http://localhost:8080 into a web browser.

or use
curl -i http://localhost:8080

You should now see something similar to the following:


HTTP/1.1 200 OK
Content-Length: 20
Content-Type: text/plain
Date: Tue, 15 Feb 2013 03:05:08 GMT
Connection: keep-alive

Thanks for calling!

curl
We can download the Windows binaries for curl by visiting
http://curl.haxx.se/download.html and looking there for the "Win32 - Generic"
section.
Download one of the highlighted binaries, preferably one with support for SSL
and SSH, unpack it, and put curl.exe somewhere in your PATH or user
directory.
To launch it, in the command prompt or PowerShell, just type
C:\Users\abc\curl --help

Wget
wget is a great alternative for curl.
We can download it from http://users.ugent.be/~bpuype/wget/.
To learn more, view the help:

C:\Users\abc\wget --help

Note
To stop the server from running, you simply press Ctrl+C.
It is smart enough to clean up everything and shut down properly.
To debug, just add the debug flag before the name of your program:
node debug web.js

Node.js vs Tranditional Web Server


Node.js is focused on creating highly performant applications.
Most web applications depend on reading data from disk or from another
network source.
Traditional Web Servers uses a Process Per Request.
Traditional servers used to spin up a new process to handle every single web
request.
Spinning a new process for each request is an expensive operation, both in
terms of CPU and memory.
Traditional Web Servers Using a Thread Pool

Example
Node.js uses a single thread to handle requests.

function longRunningOperation(callback) {
// simulate a 3 second operation

setTimeout(callback, 3000); /*from www .j a va2s . c o m*/


}

function userClicked() {
console.log('starting a long operation');
longRunningOperation(function () {
console.log('ending a long operation');
});
}
// simulate a user action
userClicked();

Node.js Data Type


Node.js is highly performant, and it uses JavaScript because JavaScript
supports first-class functions and closures.
Node.js has a few core types: number , boolean , string , and object.
The value undefined means that a value has not been set yet or simply does
not exist:

var x;
console.log(x);

The code above generates the following result.

Null
null is an explicit assertion that there "is no value":

var y;
console.log(y);

y = null ;
console.log(y);

The code above generates the following result.

typeof
To see the type of anything in JavaScript, use the typeof operator:

console.log(typeof 10);
console.log(typeof "hello");
console.log(typeof function () { var x = 20; });

The code above generates the following result.

Constants
The standard practice is to use uppercase letters and variable declarations:

var SECONDS_PER_DAY = 86400;


console.log(SECONDS_PER_DAY);

Type Comparisons and Conversions

JavaScript has both the equality operator == and the precise equality operator
===.

console.log(234 == '234');
console.log(234 === '234');
console.log(234234.235235 == 'cat');
console.log("cat" == "CAT");
console.log("cat".toUpperCase() == "CAT");

The code above generates the following result.

A number of different values evaluate to false.

console.log('' == false == null == undefined == 0);


console.log(null === undefined);

To check arguments to functions:

function fine(param) {
if (param == null || param == undefined || param == '')
throw new Error("Invalid Argument");
}
function better(param) {
if (!param)
throw new Error("Invalid Argument");
}

Pay more attention to the primitive wrapper.

var x = 234;
var x1 = new Number(234);
console.log(typeof x);
console.log(typeof x);
console.log(x1 == x);
console.log(x1 === x);

The code above generates the following result.

N
ode.js Numbers

You might also like