L’environnement de développement Node.js
Romuald THION
Semestre pair 2022 UNC
Promise
Promise
Node.js s’aligne progressivement sur le standard ES, mais les APIs historiques restent.
S’utilise, comme Python :
node file.js
A la différence de Python:
https://nodejs.org/api/events.html#events
Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called “emitters”) emit named events that cause Function objects (“listeners”) to be called.
Toute l’architecture Node.js est asynchrone, orientée événements :
Fichier events.mjs
import { EventEmitter } from "node:events";
import { setTimeout } from "node:timers/promises";
const emitter1 = new EventEmitter();
emitter1.last = Date.now();
emitter1.on("ping", async function pingListener(value, time) {
console.info(`[1] received ${value}@+${time - emitter1.last}`);
emitter1.last = time;
await setTimeout(Math.random() * 1000);
emitter2.emit("ping", value + 1, Date.now());
});
const emitter2 = new EventEmitter(); // [...] idem emitter1
> siege --benchmark --concurrent=100 --time=30s --header="Accept:application/json" 'http://127.0.0.1:8080/api-v1/'
** SIEGE 4.0.4
** Preparing 100 concurrent users for battle.
Transactions: 83395 hits
Availability: 100.00 %
Elapsed time: 29.19 secs
Data transferred: 1.27 MB
Response time: 0.03 secs
Transaction rate: 2856.97 trans/sec
Throughput: 0.04 MB/sec
Concurrency: 99.74
Successful transactions: 83395
Failed transactions: 0
Longest transaction: 0.12
Shortest transaction: 0.02
> siege --benchmark --concurrent=100 --time=30s --content-type="application/json" 'http://127.0.0.1:8080/api-v1/ POST {"url":"http://perdu.com"}'
** SIEGE 4.0.4
** Preparing 100 concurrent users for battle.
Transactions: 45210 hits
Availability: 100.00 %
Elapsed time: 29.04 secs
Data transferred: 6.42 MB
Response time: 0.06 secs
Transaction rate: 1556.82 trans/sec
Throughput: 0.22 MB/sec
Concurrency: 99.71
Successful transactions: 45210
Failed transactions: 1
Longest transaction: 0.25
Shortest transaction: 0.03
npm
est le Node Packet Manager.
npm
est à Node.js ce que pip
est à Python, avec en plus un support natif des environnements virtuels à la venv
.
package.json
{
"name": "cm4_exemples",
"version": "1.0.0",
"description": "Un exemple de serveur HTTP de base",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "DEBUG=app nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"debug": "^4.3.2",
"dotenv": "^10.0.0"
},
"devDependencies": {
"eslint": "^7.32.0",
"nodemon": "^2.0.12"
}
}
La définition du projet et ses dépendences, voir docs.npmjs.com
JSON = JavaScript Object Notation : une représentation textuelle (une serialization) des objets JavaScript
Avec le fichier package.json
précédent :
npm install
# added 296 packages in 2s
npm run dev
# > cm4_exemples@1.0.0 dev
# > cross-env DEBUG=app nodemon server.mjs
# [nodemon] 2.0.19
# [nodemon] to restart at any time, enter `rs`
# [nodemon] watching path(s): *.*
# [nodemon] watching extensions: js,mjs,json
# [nodemon] starting `node server.mjs`
# app Server listening at http://127.0.0.1:5000/ +0ms
npx
permet d’exécuter des commandes locales au dossier (dans node_modules/
) sans les installer globalement
https://www.npmjs.com/package/npx
Executes
command
either from a localnode_modules/.bin
, or from a central cache, installing any packages needed in order forcommand
to run.
npx
est implicitement utilisé par les scripts du package.json
.
/tmp/npx❯ npx cowsay "Hello world"
Need to install the following packages:
cowsay@1.5.0
Ok to proceed? (y) y
_____________
< Hello world >
-------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
/tmp/npx❯ ll
/tmp/npx❯
Plusieurs systèmes d’import de bibliothèques co-existent dans Node.js
const maLib = require('laLib');
module.exports = { ... };
.js
import maLib from 'laLib';
export default { ... };
.mjs
Préférer les modules ESM et l’extension .mjs
On donner l’exemple d’un serveur web server.mjs
avec le projet package.json
.
package.json
npm install
npm run dev
Faire la partie 1 du TP5