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

03cd82 2024

Bước 1: Tạo thư mục để chứa file, tạo file a.html trong thư mục, tạo thêm file server.js để viết code bên dưới

Bước 2: viết code bên dưới vào file server để chạy

 


// đọ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);

    if (req.url == '/a.html') {

        // http://localhost/a.html 

        // đọc file trả về trình duyệt

        fs.readFile("./a.html", function (err, data) {

            if (err) throw err; // có lỗi thì in ra và dừng các lệnh phía sau 

            // không có lỗi thì in xuống trình duyệt res.writeHead(200, {'Content-Type':'text/html'}); 

            res.write(data.toString('utf8'));

            // không gạch ngang ở utf8 
            return res.end();
        });
    } else {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write("Trang chu");

        // muốn viết tiếng Việt có dấu thì trong nội dùng write thêm thẻ: 
        return res.end();
    }
});

server.listen(80, "localhost", function () {

    console.log("Server đang chạy cổng 80: http://localhost");
});

 

 

 

 

Nguồn: zezo.dev