Allows you to build scalable network applications using JavaScript on the server-side.
Nodejs runs on V8 javascript runtime.
Let's take a look at how we create a server with nodejs, it's very simple.
var http = require('http'); server = http.createServer();
The server should "listen" on a specific port for a connection.
var http = require('http'); server = http.createServer(); server.listen(1337); console.log("Server is listening on 1337");
Now we have a running server
Nodejs is built around events.
Let's listen to the connection event on the server
var http = require('http'); server = http.createServer(); server.on('connection',function(req,res){ res.end("hello world"); }); server.listen(1337, '127.0.0.1');
What are the things that block?
Calls to other web services
In other web frameworks, we create a separate thread for each request.
An event can be, for example:
Let's look at our server, what are the events our server can have?
The only way you can block your application is that you don't end the event callback.
var http = require('http'); server = http.createServer(); server.on('connection',function(req,res){ res.writeHead("hello"); res.write("hi there"); console.log("If you don't call res.end node will stop the whole application"); console.log("This is a very common mistake"); }); server.listen(1337, '127.0.0.1');
Organize our code into files that can be included into each other We use "require" to load our module we have seen it in:
var http = require('http');
Let's create a module that:
var requestConnection = function(request){ console.log(request.headers.connection); } module.exports = requestFormatter;
use npm install "package_name"