Introduction to node.js – What is node.js ? – Node Packaged Modules



Introduction to node.js – What is node.js ? – Node Packaged Modules

0 0


clermontjs-nodejs-slides

reveals slides for ClermontJS nodejs

On Github bhtz / clermontjs-nodejs-slides

Introduction to node.js

console.log('unleash javascript !');

What is node.js ?

What is node.js ?

  • event-driven, non-blocking I/O.
  • Google Chrome V8 Engine.
  • JavaScript - async friendly.
  • NPM
  • standard library.

Single thread - Event loop

Asynchronous I/O

							
var fs = require('fs');

fs.stat('/etc/passwd', function(err, stats) {
  if (err) return;
  if (stats.isFile()) {
    fs.readFile('/etc/passwd', function(err, data) {
      if (err) throw err;
      console.log(data);
    });
  }
});		
							
						

Node Packaged Modules

Best package manager eveeeeer !

Node Packaged Modules

  • 77 679 packages (maven 71k+, nuget 23k+).
  • Bower, Grunt, Yo, CoffeeScript, TypeScript, Phonegap ...
  • global installation & local installation.

Global installation

Install :
npm install express -g
						
Use it :
express myProject --ejs
						

Local installation

Install :
npm install ejs
						
Use it :
var ejs = require('ejs');
						

package.json

{
  "name": "microscope-kernel",
  "version": "0.0.1",
  "description": "microscopejs generators engine base librairy",
  "scripts": {
    "test": "grunt test"
  },
  "author": "benjamin Heintz",
  "license": "MIT",
  "dependencies": {
    "commander": "~2.1.0",
    "inquirer": "~0.4.0",
    "ejs": "~0.8.5",
    "colors": "~0.6.2",
    "fs-extra": "~0.8.1",
    "lodash": "~2.4.1"
  },
  "devDependencies": {
    "chai": "^1.9.1",
    "grunt": "^0.4.5",
    "grunt-contrib-clean": "^0.5.0",
    "grunt-mocha-test": "^0.10.2",
    "grunt-contrib-jshint": "~0.10.0",
    "sinon": "~1.10.2",
    "sinon-chai": "~2.5.0"
  }
}
						

Modules

CommonJS

Modules

circle.js
							
var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};
							
						

Modules

foo.js
							
var circle = require('./circle.js');
var area = circle.area(4);
console.log(area);
							
						

Modules

Person.js
							
var Person = function(name, age){
  this.name = name;
  this.age = age;
};

Person.prototype.sayHello = function(){
  console.log('hello ' + this.name + ', '+ this.age +' years old');
};

module.exports = Person;
							
						

Modules

foo.js
							
var Person = require('./Person.js');
var person = new Person('bhtz', 26);
person.sayHello();
							
						

Standard library

standard library

  • os
  • filesystem
  • buffer
  • process
  • child_process
  • stream
  • assert
  • http
  • net
  • ......

HTTP server

http server in standard library.

							
var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(3000);
 
console.log('Adresse du serveur: http://localhost:3000/');
							
						

TCP Socket

							
// Load the net module to create a tcp server.
var net = require('net');

// Setup a tcp server
var server = net.createServer(function (socket) {

  // Every time someone connects, tell them hello and then close the connection.
  socket.addListener("connect", function () {
    console.log("Connection from " + socket.remoteAddress);
    socket.end("Hello World\n");
  });

});

// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
							
						

Task Runner

Build

  • Grunt
  • Gulp
  • Brocoli

Optimized SPA

  • Compile CoffeeScript - TypeScript - Less
  • Development web server
  • Minify CSS
  • Browserify - R.js

Source code - Tests

  • JsHint - JsLint
  • Mocha
  • Chai
  • Sinon

Web applications

Express.js

web application framework for node

Express.js

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

app.get('/', function(req, res){
  res.send('hello world');
});

app.get('/article/show/:id', function(req, res){
  db.Articles.find(req.params.id, function(article){
  	res.json(article);
  });
});

app.listen(3000);
							
						

Express.js

Awesome middlewares !

  • Templating (EJS, Jade, JSHTML)
  • Authentication provider (passport.js, everyAuth)
  • Logging API (log4js)
  • ORM (Sequelize, Mongoose)
  • Mailing (nodemailer)

EJS Template

JADE Template

							
doctype html
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript').
      if (foo) {
         bar(1 + 5)
      }
  body
    h1 Jade - node template engine
    #container.col
      if youAreUsingJade
        p You are amazing
      else
        p Get on it!
							
						

Real time web

Socket.IO

"featuring the fastest and most reliable real-time engine"

  • WebSocket
  • Adobe® Flash® Socket
  • AJAX long polling
  • AJAX multipart streaming
  • Forever Iframe
  • JSONP Polling

Socket.IO

							
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){

	console.log('a user connected');

	socket.on('message', function(msg){
		console.log('message: ' + msg);
	});

	socket.on('disconnect', function(){
		console.log('user disconnected');
	});
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
							
						

webRTC.IO

  • An abstraction layer for webRTC.
  • Peer to peer web browser.
  • video & audio in realtime.

Development

JavaScript .... seriously ?!!

Development

  • EcmaScript 6 -- harmony
  • Unit testing (mocha, chai, sinon)
  • Code Quality Tool (JSHint, JSLint)
  • CoffeeScript / TypeScript
  • Task runner (grunt, gulp)
  • prototyping with yeoman

IDE - Tools

  • Eclipse & Visual Studio plugins
  • WebStorm
  • Sublime Text, VIM.
  • node-inspector debugger

Hosting

Cloud ready

  • Windows azure
  • Amazon Web Services
  • Heroku
  • AppFog
  • ...

PM2

  • load balancing.
  • cluster.
  • monitoring.
  • web services.
  • json run configuration.

PM2

Enterprise ready ?

Enterprise ready ?

  • Azure mobile services
  • LinkedIn
  • Paypal
  • Uber

Already here !

  • Grunt.js
  • Azure CLI
  • Mobile hyrid apps - phonegap cli - ionic framework
  • CSS Preprocessor - less.js / stylus
  • Yeoman

Questions ?