Pour adapter votre code à un serveur Node.js brut sans utiliser Express.js, nous allons créer une structure de fichiers pour servir l'HTML, CSS et JavaScript. Voici comment procéder :
- Création du serveur Node.js :
Tout d'abord, créez un fichier nommé
server.js et placez-y le code suivant :
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// Définir le chemin du fichier à servir
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './index.html'; // Page d'accueil par défaut
}
const extname = path.extname(filePath);
let contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.gif':
contentType = 'image/gif';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
case '.woff':
contentType = 'application/font-woff';
break;
case '.woff2':
contentType = 'application/font-woff2';
break;
case '.ttf':
contentType = 'application/font-sfnt';
break;
}
// Lire le fichier et le renvoyer en réponse
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>', 'utf-8');
} else {
res.writeHead(500);
res.end('Internal Server Error: ' + error.code + ' ..\n');
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
// Écouter sur le port 3000
server.listen(3000, '127.0.0.1', () => {
console.log('Le serveur est en cours d\'exécution sur http://127.0.0.1:3000');
});
- Création des fichiers HTML, CSS, et JS :
Créez les fichiers suivants dans le même répertoire que
server.js.
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mon Navigateur Simple</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="navbar">
<button id="fullscreenBtn">Plein écran</button>
<button id="homeBtn">Home</button>
<input type="text" id="url" placeholder="Entrez une URL..." />
<input type="text" id="search" placeholder="Recherche Google..." />
<button id="searchBtn">Rechercher</button>
<button id="goBtn">Aller</button>
<button id="backBtn">Retour</button>
<button id="forwardBtn">Avancer</button>
<button id="refreshBtn">Actualiser</button>
<button id="bookmarkBtn">Marquer</button>
<button id="historyBtn">Historique</button>
<button id="darkModeBtn">Mode Sombre</button>
<button id="resizeBtn">Ajuster l'Iframe</button>
<button id="shareBtn">Partager</button>
</div>
<div id="loadingMessage" style="display:none;"></div>
<progress id="loadingBar" value="0" max="100" style="display: none;"></progress>
<iframe id="webFrame" src="" frameborder="0" sandbox="allow-same-origin allow-scripts allow-forms"></iframe>
<div id="notifications"></div>
<div id="bookmarkList" class="modal">
<div class="modal-content">
<span class="close" id="closeBookmark">×</span>
<h2>Marque-pages</h2>
<ul id="bookmarks"></ul>
</div>
</div>
<div id="historyList" class="modal">
<div class="modal-content">
<span class="close" id="closeHistory">×</span>
<h2>Historique</h2>
<ul id="historyItems"></ul>
</div>
</div>
<script src="script.js" type="module"></script>
</body>
</html>
- styles.css (identique à ce que vous avez fourni) :
body {
margin: 0;
font-family: Arial, sans-serif;
}
.navbar {
background-color: #333;
color: white;
padding: 10px;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.navbar input[type="text"] {
width: 20%;
padding: 5px;
margin-right: 5px;
}
.navbar button {
padding: 5px 10px;
margin-left: 5px;
cursor: pointer;
}
#loadingMessage {
color: red;
text-align: center;
display: none;
}
progress {
width: 100%;
height: 5px;
}
iframe {
width: 100%;
height: calc(100vh - 80px);
border: none;
}
.notifications {
position: fixed;
bottom: 20px;
left: 20px;
background-color: #333;
color: white;
padding: 10px;
z-index: 1000;
border-radius: 5px;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
.dark-mode {
background-color: #1a1a1a;
color: white;
}
.dark-mode .navbar {
background-color: #444;
}
- script.js (identique à ce que vous avez fourni) :
// Sélecteurs d'éléments
const urlInput = document.getElementById('url');
const searchInput = document.getElementById('search');
const goBtn = document.getElementById('goBtn');
const searchBtn = document.getElementById('searchBtn');
const backBtn = document.getElementById('backBtn');
const forwardBtn = document.getElementById('forwardBtn');
const refreshBtn = document.getElementById('refreshBtn');
const homeBtn = document.getElementById('homeBtn');
const bookmarkBtn = document.getElementById('bookmarkBtn');
const historyBtn = document.getElementById('historyBtn');
const darkModeBtn = document.getElementById('darkModeBtn');
const resizeBtn = document.getElementById('resizeBtn');
const shareBtn = document.getElementById('shareBtn');
const fullscreenBtn = document.getElementById('fullscreenBtn');
const webFrame = document.getElementById('webFrame');
const loadingMessage = document.getElementById('loadingMessage');
const loadingBar = document.getElementById('loadingBar');
const bookmarksDiv = document.getElementById('bookmarkList');
const historyDiv = document.getElementById('historyList');
const closeBookmark = document.getElementById('closeBookmark');
const closeHistory = document.getElementById('closeHistory');
const bookmarksList = document.getElementById('bookmarks');
const historyItemsList = document.getElementById('historyItems');
const notificationsDiv = document.getElementById('notifications');
let historyStack = JSON.parse(localStorage.getItem('historyStack')) || [];
let historyIndex = -1;
const homeURL = 'https://www.google.com';
let bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];
let isDarkMode = false;
webFrame.addEventListener('load', () => {
loadingMessage.style.display = 'none';
loadingBar.style.display = 'none';
urlInput.value = webFrame.src;
if (webFrame.src.includes('cookie')) {
alert('Ce site utilise des cookies.');
}
if (!webFrame.src.startsWith('https://')) {
showNotification("Attention : Le site n'utilise pas HTTPS.");
}
saveHistory(webFrame.src);
});
webFrame.addEventListener('error', () => {
showNotification('Erreur de chargement de la page. Vérifiez l\'URL.');
});
webFrame.addEventListener('loadstart', () => {
loadingMessage.innerText = 'Chargement...';
loadingMessage.style.display = 'block';
loadingBar.style.display = 'block';
loadingBar.value = 0; // Réinitialiser la barre de chargement
});
const interval = setInterval(() => {
if (loadingBar.value < 99) {
loadingBar.value++;
}
}, 100);
webFrame.addEventListener('loadend', () => {
clearInterval(interval);
loadingBar.value = 100; // Remplir complètement la barre
});
// Événements pour le bouton "Go"
goBtn.addEventListener('click', () => {
loadURL(urlInput.value.trim());
});
// Événements pour le bouton "Rechercher"
searchBtn.addEventListener('click', () => {
const query = searchInput.value.trim();
loadURL(`https://www.google.com/search?q=${encodeURIComponent(query)}`);
});
// Événements pour charger avec la touche "Entrée"
urlInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
loadURL(urlInput.value.trim());
}
});
searchInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
const query = searchInput.value.trim();
loadURL(`https://www.google.com/search?q=${encodeURIComponent(query)}`);
}
});
// Événements pour le bouton "Home"
homeBtn.addEventListener('click', () => {
loadURL(homeURL);
});
// Événements pour le bouton "Retour"
backBtn.addEventListener('click', () => {
if (historyIndex > 0) {
historyIndex--;
webFrame.src = historyStack[historyIndex];
urlInput.value = historyStack[historyIndex];
}
});
// Événements pour le bouton "Avancer"
forwardBtn.addEventListener('click', () => {
if (historyIndex < historyStack.length - 1) {
historyIndex++;
webFrame.src = historyStack[historyIndex];
urlInput.value = historyStack[historyIndex];
}
});
// Événements pour le bouton "Actualiser"
refreshBtn.addEventListener('click', () => {
webFrame.src = webFrame.src;
});
// Fonction pour charger une URL
function loadURL(url) {
// Ajout de "http://" et correction d'URL
if (!/^https?:\/\//i.test(url)) {
url = 'http://' + url;
}
webFrame.src = url;
// Mettre à jour l'historique
if (historyStack[historyIndex] !== url) {
historyStack = historyStack.slice(0, historyIndex + 1);
historyStack.push(url);
historyIndex++;
localStorage.setItem('historyStack', JSON.stringify(historyStack));
}
}
// Sauvegarder l'historique dans le stockage local
function saveHistory(url) {
if (!historyStack.includes(url)) {
historyStack.push(url);
localStorage.setItem('historyStack', JSON.stringify(historyStack));
}
}
// Action du bouton "Marquer"
bookmarkBtn.addEventListener('click', () => {
const currentURL = webFrame.src;
if (!bookmarks.includes(currentURL)) {
bookmarks.push(currentURL);
updateBookmarks();
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
showNotification('Page marquée !');
} else {
showNotification('La page est déjà dans les marque-pages.');
}
});
// Afficher la liste des marque-pages
bookmarkBtn.addEventListener('click', () => {
bookmarksDiv.style.display = 'block';
});
// Fermer la liste des marque-pages
closeBookmark.addEventListener('click', () => {
bookmarksDiv.style.display = 'none';
});
// Mettre à jour la liste des marque-pages affichée
function updateBookmarks() {
bookmarksList.innerHTML = '';
bookmarks.forEach((bookmark) => {
const li = document.createElement('li');
li.textContent = bookmark;
li.onclick = () => loadURL(bookmark);
bookmarksList.appendChild(li);
});
}
// Événements pour afficher l'historique
historyBtn.addEventListener('click', () => {
historyDiv.style.display = 'block';
updateHistory();
});
// Fermer l'historique
closeHistory.addEventListener('click', () => {
historyDiv.style.display = 'none';
});
// Mettre à jour l'affichage de l'historique
function updateHistory() {
historyItemsList.innerHTML = '';
historyStack.forEach((item) => {
const li = document.createElement('li');
li.textContent = item;
li.onclick = () => loadURL(item);
historyItemsList.appendChild(li);
});
}
// Gestion du mode sombre
darkModeBtn.addEventListener('click', () => {
isDarkMode = !isDarkMode;
document.body.classList.toggle('dark-mode', isDarkMode);
});
// Passer en mode plein écran
fullscreenBtn.addEventListener('click', () => {
if (webFrame.requestFullscreen) {
webFrame.requestFullscreen();
} else if (webFrame.webkitRequestFullscreen) { // Safari
webFrame.webkitRequestFullscreen();
} else if (webFrame.msRequestFullscreen) { // IE11
webFrame.msRequestFullscreen();
}
});
// Fonction pour afficher les notifications
function showNotification(message) {
const notification = document.createElement('div');
notification.className = 'notifications';
notification.innerText = message;
document.body.appendChild(notification);
setTimeout(() => {
document.body.removeChild(notification);
}, 3000);
}
// Raccourcis clavier
document.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.key === 'l') {
urlInput.focus();
}
if (event.ctrlKey && event.key === 'r') {
refreshBtn.click();
}
});
- Exécution du serveur :
Dans le terminal, naviguez vers le répertoire où se trouvent ces fichiers et exécutez la commande suivante :
node server.js
Cela démarrera le serveur sur http://127.0.0.1:3000. Vous pouvez alors ouvrir ce lien dans un navigateur pour voir votre "navigateur simple" en action.
Avec cette structure, le serveur Node.js sert les fichiers statiques (HTML, CSS, JS) sans avoir besoin d'Express.js.