Node.js est un outil gratuit et open source qui permet d'exécuter des scripts JavaScript côté serveur.
Il fonctionne sur Windows, Mac, Linux et plus encore.
Construit sur le moteur JavaScript V8 de Chrome, Node.js est conçu pour créer efficacement des applications réseau évolutives telles que des serveurs Web, des API, des outils, etc...
Utilisé par: GoDaddy, IBM, Netflix, Amazon Web Services, Groupon, Vivaldi, SAP, LinkedIn, Microsoft, Yahoo!, Walmart, Rakuten, Sage, PayPal, Discord, Myspace ...
Pour simplifier la programmation le code est orienté sur les évènements: programmation évènementielle. Non bloquant asynchrone.
Node.js excelle dans la gestion de nombreuses connexions simultanées avec une surcharge minimale, ce qui le rend parfait pour:
- Real-time applications (chats, gaming, collaboration tools)
- APIs and microservices
- Data streaming applications
- Command-line tools
- Server-side web applications
- Web Servers: Create fast, scalable network applications
- File Operations: Read, write, and manage files on the server
- Database Interaction: Work with databases like MongoDB, MySQL, and more
- APIs: Build RESTful services and GraphQL APIs
- Real-time: Handle WebSockets for live applications
- CLI Tools: Create command-line applications
Installation sur Ubuntu
$ sudo apt update $ sudo apt install nodejs Les paquets supplémentaires suivants seront installés : libcares2 libnode109 node-acorn node-busboy node-cjs-module-lexer node-undici node-xtend nodejs-doc Paquets suggérés : npm Les NOUVEAUX paquets suivants seront installés : libcares2 libnode109 node-acorn node-busboy node-cjs-module-lexer node-undici node-xtend nodejs nodejs-doc 0 mis à jour, 9 nouvellement installés, 0 à enlever et 29 non mis à jour. Il est nécessaire de prendre 16,1 Mo dans les archives. $ sudo apt install npm Les NOUVEAUX paquets suivants seront installés : 0 mis à jour, 388 nouvellement installés, 0 à enlever et 29 non mis à jour. Il est nécessaire de prendre 14,4 Mo dans les archives. Vérifier qu'ils tournent: $ nodejs -v v18.19.1 $ npm -v 9.2.0 Pour les supprimer: $ sudo apt remove nodejs $ sudo apt remove npm
INSTALLATION SANS APT en SSH
(server):user42:~$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash (server):user42:~$ nvm install 24 v24.2.0 is already installed. Now using node v24.2.0 (server):user42:~$ node -v v24.2.0 (server):user42:~$ npm -v # # Fatal process out of memory: Failed to reserve virtual memory for CodeRange # ----- Native stack trace ----- 1: 0x112aa91 [node] 2: 0x2ce56b5 v8::base::FatalOOM(v8::base::OOMType, char const*) [node] 3: 0x1351def [node] 4: 0x1351e8f v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node] 5: 0x15f5bbe v8::internal::Heap::SetUp(v8::internal::LocalHeap*) [node] 6: 0x152836e v8::internal::Isolate::Init(v8::internal::SnapshotData*, v8::internal::SnapshotData*, v8::internal::SnapshotData*, bool) [node] 7: 0x1afcb83 v8::internal::Snapshot::Initialize(v8::internal::Isolate*) [node] 8: 0x137c006 v8::Isolate::Initialize(v8::Isolate*, v8::Isolate::CreateParams const&) [node] 11: 0x1033746 node::Start(int, char**) [node] 12: 0x7f5395d6bd7a __libc_start_main [/lib/x86_64-linux-gnu/libc.so.6] 13: 0xf6576e _start [node] Trappe pour point d'arrêt et de trace (server):user42:~$ nvm install 10.24.1 (server):user42:~$ node test.js Server running on http://localhost:8080 Complété (server):user42:~$Première application
test.jsconst http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World!'); }).listen(8080); console.log(`Server running on http://localhost:8080`);Lancer le serveur:$ node test.js Server running on http://localhost:8080 Pour stopper le serveur: CTRl-CEt tester dans le navigateur avec l'URL http://localhost:8080
MODULES
Liste des built-in modules NPM signifie Node Package Manager.
It helps you install and manage third-party packages (libraries) to add more features to your apps.$ npm install expressconst express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Hello World!')); app.listen(8080);OU créer un fichier package.json package.json is the heart of any Node.js project, containing metadata, scripts, and dependency information et$ npm install Install a package globally: $ npm install -g package-name $ npm update package-name Update all packages in your project: $ npm update Check for outdated packages: $ npm outdated Remove a package: $ npm uninstall package-name Remove a global package: $ npm uninstall -g package-name Remove a package and its dependencies: $ npm uninstall --save package-name Créer package.json $ npm init For a quick setup with default values, use: $ npm init -yApplication de chat
package.json{ "name": "chat-app", "version": "1.0.0", "description": "Simple chat app using Node.js and Socket.IO", "main": "server.js", "scripts": { "start": "node server.js" }, "dependencies": { "express": "^4.18.2", "socket.io": "^4.7.2" } }server.jsconst express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const app = express(); const server = http.createServer(app); const io = new Server(server); app.use(express.static('public')); io.on('connection', (socket) => { console.log('A user connected'); io.emit('join message', 'un client a rejoint le chat'); socket.on('chat message', (msg) => { io.emit('chat message', msg); // broadcast to all clients }); socket.on('disconnect', () => { console.log('User disconnected'); io.emit('quit message', 'un client a quitté le chat'); }); }); const PORT = process.env.PORT || 3000; server.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });public/index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Chat App</title> <style> body { font-family: Arial, sans-serif; padding: 20px; } ul { list-style: none; padding: 0; } li { margin-bottom: 10px; } input { padding: 10px; width: 80%; } button { padding: 10px; } </style> </head> <body> <h1>Chat Room</h1> <ul id="messages"></ul> <form id="form"> <input id="input" autocomplete="off" placeholder="Type a message..." /> <button>Send</button> </form> <script src="/socket.io/socket.io.js"></script> <script> const socket = io(); const form = document.getElementById('form'); const input = document.getElementById('input'); const messages = document.getElementById('messages'); form.addEventListener('submit', function(e) { e.preventDefault(); if (input.value) { socket.emit('chat message', input.value); input.value = ''; } }); socket.on('join message', function(msg) { const item = document.createElement('li'); item.textContent = msg; item.style.backgroundColor = 'orange'; messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight); }); socket.on('chat message', function(msg) { const item = document.createElement('li'); item.textContent = msg; messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight); }); socket.on('quit message', function(msg) { const item = document.createElement('li'); item.textContent = msg; item.style.backgroundColor = 'orange'; messages.appendChild(item); window.scrollTo(0, document.body.scrollHeight); }); </script> </body> </html>Et ouvrir 2 fenêtres http://localhost:3000/Read a File Asynchronously
// Load the filesystem module const fs = require('fs'); // Read file asynchronously fs.readFile('myfile.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading file: ' + err); return; } console.log('File content: ' + data); }); console.log('Reading file... (this runs first!)');