tgoop.com/we_use_js/4093
Create:
Last Update:
Last Update:
Создайте HTTP-сервер на Node.js, который раздаёт статические файлы из указанной папки. По умолчанию сервер должен обслуживать файлы из папки public и работать на порту 3000.
Создайте структуру папок:
project/
├── server.js
└── public/
└── index.html
Решение задачи
Файл server.js:
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const PUBLIC_DIR = path.join(__dirname, 'public');
const server = http.createServer((req, res) => {
let filePath = path.join(PUBLIC_DIR, req.url === '/' ? 'index.html' : req.url);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
});
server.listen(PORT, () => {
console.log(`Сервер запущен на http://localhost:${PORT}`);
});
Файл public/index.html (пример содержимого):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Static Server</title>
</head>
<body>
<h1>Добро пожаловать на мой сервер!</h1>
</body>
</html>
node server.js