Node.js – Introduction – Architecture



Node.js – Introduction – Architecture

0 0


lightning-talk-nodejs

Lightning Talk - Introduction to Node.js

On Github purplecode / lightning-talk-nodejs

Node.js

Introduction

by Mateusz Jaworski

April 2016

  • open-source, cross-platform, MIT license
  • asynchronous, event driven
  • event loop as a language construct not library
  • shell/repl (read-eval-print-loop)
  • npm - package manager
  • other: Twisted (python), Vert.x (Java, Ruby, Scala, Clojure...)

History

  • 2009 - originally written by Ryan Dahl
  • 2011 - added npm and support for Windows
  • 2014 - Fedor Indutny started io.js, a fork of Node.js
  • 2015 - Node.js v0.12 and io.js v3.3 merged back into Node v4.0

Node.js Foundation

The Node.js Foundation's mission is to enable widespread adoption and help accelerate development of Node.js and other related modules through an open governance model that encourages participation, technical contribution, and a framework for long term stewardship by an ecosystem invested in Node.js' success.
  • Node.js is a trademark of Joyent, Inc. (high-performance cloud computing)
  • Foundation corporate members: IBM, Intel, Microsoft, RedHat, PayPal, Joyent...
  • ~300 active contributors (~900 in total)

Architecture

@source:  An Inside Look at the Architecture of NodeJS

Architecture

  • core written in C, C++
  • single main thread, non-blocking I/O calls
  • no cost of thread context switching
  • thread pool for parallel tasks, when done main thread wakes up and executes the registered callback
  • registered within operating system, operating system issues a callback on connection

Google’s V8 JavaScript engine

  • compiles JavaScript into native code
  • garbage collector
  • optimizer
  • re-optimizer (at runtime)
    • based on heuristics of the code's execution profile
    • inline expansion
    • inline caching
    • copy elision

libuv - multi-platform asynchronous I/O

  • developed for use by Node.js, also used by others
  • event loop
  • asynchronous TCP/UDP sockets and DNS resolution
  • asynchronous file system operations
  • child processes
  • thread pool

Miscellaneous

  • possibility to write C++ addons
  • debugging - IDE ot Chrome Dev Tools
  • build in modules: fs, os, path, querystring, zlib, vm, crypto
  • globals: console, require, process, module, exports, global

Code

Frameworks

  • Express.js, Hapi.js, Koa.js - minimalist
  • Socket.io - for real-time apps
  • Sails, Derby - MVC frameworks
  • Meteor - pure magic

Basics

var http = require('http');

var handleRequest  = function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hit: ' + req.url);
};

http.createServer(handleRequest).listen(3000, function () {
    console.log("Server listening on: http://localhost:3000");
});

Express

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

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

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

app.listen(3000, function () {
    console.log("Server listening on: http://localhost:3000");
});

Express - static content

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

app.use('/static', express.static(__dirname + 'public'));

app.listen(3000, function () {
    console.log("Server listening on: http://localhost:3000");
});

Express - jade templates

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

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.get('/', function(req, res){
    res.render("index", {message: 'Hello world!'});
});

app.listen(3000, function () {
    console.log("Server listening on: http://localhost:3000");
});
views/index.jade
html
  head
    title title
  body
    h1= message

Live demo

npm install express-generator -g
express myapp

Forever

npm install forever -g
forever start app.js
NODE_ENV=production forever start -l forever.log -o out.log -e err.log app.js
forever list
forever stop app.js
forever stopall

Scaling

Scaling - cluster

const cluster = require('cluster');
const http = require('http');
const numberOfCpus = require('os').cpus().length;

function spawnMaster() {
    for (var i = 0; i < numberOfCpus; i++) {
        cluster.fork();
    }
    cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
    });
}

function spawnFork() {
    // Workers can share any TCP connection, in this case it is an HTTP server
    http.createServer((req, res) => {
        res.writeHead(200);
        res.end('hello world\n');
    }).listen(8000);
}

cluster.isMaster ? spawnMaster() : spawnFork();

Scaling - forks

main.js
const child_process = require('child_process'); const fork = child_process.fork('fork.js'); fork.on('message', message => { console.log('Parent got message: ', message); }); fork.send({ data: 123 });
fork.js
process.on('message', message => { console.log('Child got message:', message); process.send({ data: 456 }); });

Future

  • long-term support plan (LTS)
  • Microsoft Chakra Core engine usage
  • involvement of large companies like Intel, Microsoft and IBM
  • IoT, Mobile

This is all for now...

Thanks!