Node.js

A Brief Introduction

Thameera Senanayaka

Allion Technologies

What's Node.js?

  • Lets you run JavaScript on the server side
  • Uses the Google V8 JavaScript engine
    • Used in Google Chrome
    • Written in C++
  • Open source
  • Runs on Linux, OS X, Windows, FreeBSD

History

  • First written in 2009
  • By Ryan Dahl from Joyent
  • Soon to be managed by Node.js Foundation
  • Current version 0.12.4

Simple node.js app

console.log('Hello world!');

app.js

How to run a Node.js app

  • Node is a command line tool
$ node app.js
Hello world!
$

Creating a Server

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200);
  res.end('Hello World!');
}).listen(8000);

console.log('Listening on port 8000');

Non-blocking IO

var results = db.query('select * from person');
process(results);

// more code
db.query('select * from person', function(results) {
  process(results);
});

// more code

Non-blocking

Blocking

Package management

$ npm install express
var express = require('express');

app.js

NPM modules

Express Web Framework

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

var server = app.listen(8000, function () {
  console.log('Listening on port 8000');
});
var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.get('/user', function(req, res) {
  /* */
});

app.post('/user', function(req, res) {
  /* */
});

var server = app.listen(8000, function () {
  console.log('Listening on port 8000');
});

Express - Adding more routes

Thank you!

NodeJS

By Thameera