Node.js

Introduction

François de Metz - francois2metz

Stormz

Sondage express

Nodejs c'est

Décideurs pressés, ne partez pas tout de suite

Qui l'utilise dans le monde ?

Hello world

console.log('Hello world')
setTimeout(function() {
  console.log('world')
}, 2000)
console.log('Hello')

Require

var url = require('url')

console.log(url.parse('http://nodejs.org/api/url.html'))

Requêtes HTTP

var http = require('http')

http.get({host: 'duckduckgo.com'}, function(res) {
    console.log(res.statusCode)
})

Serveur HTTP

var http = require('http')

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('Hello World\n')
}).listen(1234)

Un vrai programme

var http = require('http')

var lastStatus = -1

setInterval(function() {
    http.get({host: 'duckduckgo.com'}, function(res) {
        console.log(res.statusCode)
        lastStatus = res.statusCode
    })
}, 5000)

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'})
    res.end('last status of duckduckgo:'+ lastStatus +'\n')
}).listen(1234)

Les IO sont non bloquantes

Démonstration

var http = require('http')

console.log('currend pid', process.pid)

http.createServer(function (req, res) {
    setTimeout(function() {
        res.writeHead(200, {'Content-Type': 'text/plain'})
        res.end('Hello World from pid '+ process.pid +'\n')
    }, 2000)
}).listen(1234)

Event Loop / reactor pattern

Avantages

Inconvénient

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

Cluster

var cluster = require('cluster')
var http = require('http')
var numCPUs = require('os').cpus().length

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork()
  }

  cluster.on('death', function(worker) {
    console.log('worker ' + worker.pid + ' died')
  })
} else {
  // Worker processes have a http server.
  http.Server(function(req, res) {
    console.log('Hello from pid', process.pid)
    setTimeout(function() {
        res.writeHead(200, {'Content-Type': 'text/plain'})
        res.end('Hello World from pid '+ process.pid +'\n')
    }, 2000)
  }).listen(1234)
}

NPM (Node Package manager)

npm install underscore

npm install -g coffee-script

npm install

Créer un module

package.json

{
  "name": "parisjs-website",
  "version": "0.0.1",
  "main": "./utils/meetups.js",
  "dependencies": {
      "jsdom": "",
      "underscore": ""
  },
  "devDependencies": {}
}
exports.plop = function() {
    return 'plop'
}

Questions?

François de Metz - francois2metz - francois@2metz.fr