1 of 12

La programmation event-driven pour le back

2 of 12

Node.js

V8

libuv

HTTPS

FileSystem

REPL

NPM

3 of 12

Event loop

“Wayward Carousel: JS Streams” by Kayla Comalli

https://codeburst.io/wayward-carousel-js-streams-7f6a6d950180

4 of 12

Démarrer un projet Node.js

mkdir dojo-node

cd dojo-node

npm init

console.log("Hello World");

node main.js

Hello World

node

> console.log(“Hello”)

Hello

> 5+6

11

Shell

main.js

Shell

5 of 12

Notre projet du jour

Une API qui donne les infos sur les stations VCub

6 of 12

Notre projet du jour

https://api.citybik.es/v2/networks

7 of 12

HTTPS (Requête)

const https = require("https");

https.get("https://google.com", (result) => {

result.on("data", (data) => {

// Receive data

});

result.on("end", () => {

// All data received

});

});

8 of 12

File System

const fs = require("fs");

fs.readFile(`fichier.json`, (error, data) => {

// …

});

fs.writeFile("fichier.json", "contenu", (error) => {

// …

});

fs.mkdir("dossier", () => {

// …

});

9 of 12

HTTP (Serveur)

const http = require("http");

const server = http.createServer((request, result) => {

console.log("Handling request to ", request.url);

// …

result.write("OK");

result.end();

});

server.listen(8080);

10 of 12

Callback Hell

doSomething((a) => {

doSomethingElse((b) => {

doSomething((c) => {

doSomethingElse((d) => {

doSomething((e) => {

doSomethingElse((f) => {

console.log(a, b, c, d, e, f);

});

});

});

});

});

});

11 of 12

Callback Hell

async function do() {

const a = await doSomething();

const b = await doSomethingElse();

const c = await doSomething();

const d = await doSomethingElse();

const e = await doSomething();

const f = await doSomethingElse();

console.log(a, b, c, d, e, f);

}

12 of 12

A word on concurrency

Single thread

Child processes

Cluster : Partage des file descriptors (fichiers ou réseaux)

Workers : Partage de la mémoire