La programmation event-driven pour le back
Node.js
V8
libuv
HTTPS
FileSystem
REPL
NPM
Event loop
“Wayward Carousel: JS Streams” by Kayla Comalli
https://codeburst.io/wayward-carousel-js-streams-7f6a6d950180
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
Notre projet du jour
Une API qui donne les infos sur les stations VCub
Notre projet du jour
https://api.citybik.es/v2/networks
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
});
});
File System
const fs = require("fs");
fs.readFile(`fichier.json`, (error, data) => {
// …
});
fs.writeFile("fichier.json", "contenu", (error) => {
// …
});
fs.mkdir("dossier", () => {
// …
});
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);
Callback Hell
doSomething((a) => {
doSomethingElse((b) => {
doSomething((c) => {
doSomethingElse((d) => {
doSomething((e) => {
doSomethingElse((f) => {
console.log(a, b, c, d, e, f);
});
});
});
});
});
});
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);
}
A word on concurrency
Single thread
Child processes
Cluster : Partage des file descriptors (fichiers ou réseaux)
Workers : Partage de la mémoire