Code nodejs sử dụng module fs đọc file html trả về client 2

03cd82 2024
// đọc file html trả về trình duyệt 
const http = require("http");
// sử dụng module fs để đọc file const fs = require("fs"); 
console.log("Bắt đầu tạo server...");
const server = http.createServer(function (req, res) {
    console.log("Truy cập: " + req.url);
    // nếu vào trang c.html thì tự chuyển về trang a.html 
    // còn lại thì tự load file và show lên 
    if (req.url == '/c.html') {
        // tự động chuyển sang địa chỉ mới 
        console.log("Chuyển sang địa chỉ mới vì không tồn tại c.html");
        res.writeHead(301, { 'Location': 'http://' + req.headers['host'] });
        return res.end();
        // kết thúc
    } else if (req.url == '/') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        return res.end("<h1>Trang home</h1>"); // trang chủ
    } else {
        // đọc file và trả về nội dung
        fs.readFile(req.url.substring(1),
            function (err, data) {
                if (err) console.log(err);
                else res.write(data.toString('utf8'));
                return res.end();
            }); return res.end();
    }
});
server.listen(80, "localhost", function () {
    console.log("Server đang chạy cổng 80: http://localhost");
});
Nguồn: zezo.dev