Node.js

WHAT IS NODE.JS

Node.js is a platform built on Chrome’s JavaScript runtime for
easily building fast, scalable network applications.

Node.js uses an
event-driven, non-blocking I/O model that makes it lightweight and
efficient, perfect for data-intensive real-time applications that run
across distributed devices.
thread.

WHAT IS NODE.JS

  • Created in 2009 by Ryan Dahl
  • JavaScript that’s outside of the browser. It can be used to build web servers, command line interfaces, anything that exists outside the browser.
  • Uses the Google V8 JavaScript engine to execute JS (super fast)
  • Single-threaded, event-driven & non-blocking I/O model
  • It is 40 % Js and 60 % C++

WHAT IS NODE.JS

  • Open source (github)
  • Cross-platform (Linux, FreeBSD, OSX, Windows, etc)
  • JavaScript interpreter (make it accessible to web dev)
  • console based (allows easy use of stdin, stdout pipe)
  • supports modules (which allow building of frameworks)
  • non-blocking
  • primarily used to build network programs and tools

WHY NODE.JS

  • You need a fast web server that can handle 100,000+ concurrent connections with ease
  • You know JS already and need a web server
  • Ideal applications
    • JSON APIs, streaming data, dashboard for stock trader
  • ​Bad applications
    • CPU intensive operations (Calculating Pi to 100m digits, cognitive computing algorithms, etc.)

WHAT TO USE NODE FOR

  • Ideal for building fast, scalable real-time applications
  • Push technology over WebSockets 
  • Handles two-way connections extremely well

SAMPLE APPLICATIONS

  • Chat server
  • API on top of object store like MongoDB
  • Queueing inputs to a db when receiving large amounts of concurrent data — such as real-time analytics
  • Server-side proxy (like NGINX)
  • Use Node stack for single page app dev
  • Excellent for prototyping!

TO BE OR NOT TO BE

SYNCHRONOUS

$db = $this->getDatabase();

$query = 'SELECT giant_field, COUNT(field) AS counter
    FROM massive_table mt
    LEFT JOIN even_bigger_table ebt ON mt.field1 = ebt.field2
    WHERE ebt.field3 = \'Zosia\'
    ORDER BY mt.date DESC
    HAVING counter > 1000';

$result = $db->query($query)->fetchAll();

WHAT IS THE SOFTWARE DOING WHILE IT QUERIES A DATABASE?

NOTHING
IT JUST WAITS FOR THE RESPONSE...

TO BE OR NOT TO BE

Process

request

Query

Database

Fetching

Result

Process

Response

Send 

Response

WHAT SERVER'S CPU IS DOING

SERVER IS WAITING FOR THE I/O

Node.js Eveny loop

EVENT LOOP CPU UTILIZATION

  • JuSt small gaps for context switching

  • One thread, many consequent requests

  • Separated IO operations

ONE REQUEST MEMORY USAGE

Tomcat
IIS
Apache
lighttpd
nginx
Node.js

198 MB
155 MB
50 MB
18 MB
8 MB
3 MB

Node.js vs Apache2

Node.js vs Apache2

Node.js is *FAST*

  • V8 based JS runtime
  • Event driven
  • Non-blocking I/O

NODE.JS REPL

A Read-Eval-Print-Loop (REPL) stand alone program comes with node and can be run via command line.

➜ node
> 2 + 4
6
> console.log("Hello")
"Hello"
> function sayHi(message){console.log(message)}
undefined
> sayHi("Hi There")
"Hi There"

CREATING & EXECUTING A NODE.JS FILE

A Node.js file is just a Javascript file. It's identical in most ways to client-side Javascript files. Example:

var testing = 12345;
function printStuff(stuff){
    console.log(stuff);
}
printStuff(testing);

Execute a JS file with Node.js:

➜  ~ node app.js

NODE MODULES

  • Modules allow you to bring in external functionality into your Node app
  • Modules can export variables, functions and objects 
  • Three main sources of Node modules
    • Node’s built-in modules — fs, http, os
    • Third party modules from npm
    • Creating your own modules
  • Modules are a great way to organize your code

USING MODULES

  • Create a function, make it available with either exports or module.exports
  • Use it with require
// create module hello.js
var hello = function(){
   console.log('hello!') 
}; 
module.exports = hello;

// use the module in your main server file
var hello = require('./hello');
hello();
  

CREATING A MODULE

To expose your module of javascript code for other files to import/use, you need to use the 'module.exports' command:

//superhero.js

var superhero = {
    saveTheDay: function (arg1, arg2, arg3){
        //do something supernatural
        //display that supernatural thing
    }
}

module.exports = superhero;

COMMONJS FORMAT

  • Node.js uses the CommonJS format for modularity
  • Importing a module into your file:
require('./relative/path/to/module');

This module can now be used in your file:

var instanceOfSuperhero = require('./js/superhero');

instanceOfSuperhero.saveTheDay('Location', 'Time', 'Person');

IMPORTING MODULES BASED ON ORIGIN

Core Node Modules (Like 'http'):

require('http');

Your custom modules

require('./relative/path/to/module');

3rd party modules installed via NPM (stored in 'node_modules'' folder):

require('express');

CREATING A SERVER WITH JUST NODE.JS

  • Node.js comes with a powerful API that can create a powerful web server without any 3rd party code.
  • Simple 'GET' request example:
//Import Node's http module
var http = require('http');
 
//create a server
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'}); //creating a response header
  res.end('Hello World\n'); // creating response body.
})
.listen(3000); // open port 3000 to recieve requests and keep server listening
 
// Reminder for us what port we setup our server on
console.log('Server running on port 3000');

NPM

  • Node Package Manager (NPM) is the official repository for server-side JS, with tons of client-side JS as well
  • Common NPM modules include ExpressJS, Mongoose, Cordova, Grunt, Gulp and Browserify.
  • The NPM ecosystem is completely open and anyone can create a package for others to use
  • It makes your life as a developer 1 billion times easier :)

PACKAGE.JSON

  • To use NPM for your Node.js application, you must use a 'package.json' file to track the modules you use.
  • This file can also be used to store mountains of other useful info about your application like the author's name, git repository, license and much more.
  • After this file is created, a folder named 'node_modules' will be created to store modules you download/install

EXAMPLE PACKAGE.JSON

{
  "name": "browserify",
  "version": "10.2.4",
  "description": "browser-side require() the node way",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "http://github.com/substack/node-browserify.git"
  },
  "keywords": [
    "browser"
  ],
  "dependencies": {
    "browser-pack": "^5.0.0",
    "vm-browserify": "~0.0.1",
    "xtend": "^4.0.0"
  },
  "author": {
    "name": "James Halliday",
  },
  "scripts": {
    "test": "tap test/*.js"
  }
}

CREATING PACKAGE.JSON

To create, use 'npm init' command:

➜  ~ npm init

Follow the prompts from there to create your file.

USING NPM

To download a package to your local machine:

npm install packagename

Install multiple packages:

npm install package1 package2 package3 etc

To record packages to 'package.json' file:

npm install packagename --save

USING A FRAMEWORK WITH NODE.JS

  • NPM is full of enterprise grade 3rd party frameworks for everything you can think of - handling HTTP connections, interacting with databases, social media APIs, authentication, you name it.
  • We will use a popular web framework for building Node.js applications called Express.

EXPRESS.JS

  • Built-in HTTP server
  • Request / response enhancements
  • View support
  • HTML & redirection helpers
  • Ability to create robust APIs quickly & easily
  • Model - View - Router architecture
  • Does not hide any Node functions

EXPRESS

  • Express is the most popular web framework for Node.js
  • It has a simple API to for HTTP communications in Node.js
var express = require('express');
var app = express();

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

app.listen(3000);

EXPRESS

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

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

var server = app.listen(3000, 'localhost', function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log(`Example app listening at http://${host}:${port}`);
});

Another example

INSTALL EXPRESS WITH NPM

Installing Express with NPM

npm install express --save

The '--save' flag will save this as a dependency in your 'package.json' file. Open it up to check it out

CREATING A SERVER WITH EXPRESS

  • Use the Express API Docs to expand its capabilities and build your own creation.
  • It's helpful to use nodemon to automatically restart your server when changes are made.

Get Method

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

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

app.use(bodyParser.json()); // for parsing application/json

// for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/get_method', function (req, res) {
    res.send(`Hello ${req.query.name}`);
});

var server = app.listen(3000, 'localhost', function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log(`Example app listening at http://${host}:${port}`);
});

Useful Links

https://nodejs.org Node.js

http://learn.javascript.ru/screencast/nodejs Скринкаст NODE.JS

http://nodebeginner.ru/ Node.js для начинающих

http://theasder.github.io/tutorial/2014/05/16/beginners-guide-to-nodejs.html Руководство для начинающих в Node.js

http://thinking.bohdanvorona.name/to-learn-node-js/ С чего начать изучение Node.js

http://nodeguide.ru/doc/ Руководства по Node.js

THANKS FOR YOUR ATTENTION

Node.js

Node.js

By Dima Pikulin

Node.js

  • 994