Monday, May 25, 2015

What is node.js


Node is
1. A set of bindingisg to v8 for non browser work: sockets, files,

etc
2. Only exposes non-blocking, ashnychrous interfaces.
3. Only one thread, one call stack ( like the browser)
4. Low level features : E.G half closed TCP connection, TCP

throttling, UDP.
5. Has killer HTTP support.

Because the interface is purely non-blocking, users tend to achieve

decent concurrency without knowing what they are doing.
Non-blocking jail.

. No Mutex locks
. only one thing at a time
. no thread safety issue.
. Almost no side effects once event is emitted.

Node architect:
Node Standered liberary -- java script
node bindingis           -- c++ -- non blocking process calls
v8|thread pool|event loop -- c

Examples:

Node is command line tool. you have to download it and install it.

No dependencies other than python for the build system. V8 is

included in the distribution.
1. setTimeout(function(){
  console.log('wprld');
},2000);

console.log('hello');

A programs which prints "hello", wait 2 sec , ouputs "worlds" and

then exist.
SO node always exist after there is no other callbacks to be

completed.When the event loop has no timeouts or file descriptors

on it, it exists automatically.

example 2.
Every 500ms print "hello"
on SIGINT print "buy"
Using the special process object.
--> In node, you have this process global variable. it's kind of

the node is very process oriented.

setInterval(function() {

console.log('hello');
},500);

Process.on('SIGINT' function() {
    console.log('bye');
process.exit(0);   --> setting a callback, we are listening for the

SIGINT event on the process object.

Like process, many other objects in Node emit events.
A TCP server emits a "connection" event each time someone conects.
A HTTP upload emits a "data" event on each packet.

Event emitting is the kind of the fundamental in the node.

Example3.
A program which:
Starts a TCP server on port 8000
Send the peer a message
Colse the connection

--> This requires a module. Require is how you load a module in

node, this is the common JS module specification. So, you load the

net module, which is how u create a TCP server and do

net.createServer, it gives you a server and then you listen to the

connection event on that object. That connection event gives you a

call back with a socket which we call c here. And all you do is you

- on that callback, you do c.end, which send the argument to the

connection and cloases the connection.

net = require("net");

s=net.createServer();

net.on('connection', function(c){
c.end('hello');
});

s.listen(8000);