Code đọc file html trong nodejs

03cd82 2024

Bước 1: Tạo 1 thư mục là DocFile, bên trong tạo file index.js với nội dung bên dưới.

Bước 2: Tạo file a.html với nội dung html bất kỳ

Bước 3: Chạy node index.js sau đó vào trình duyệt web nhập vào địa chỉ /a.html để xem kết quả có load được file html lên không

 

const http = require("http")
const fs = require('fs');
const { join } = require("path");
server = http.createServer((req, res) => {
    console.log(req.url);
    if (req.url == '/favicon.ico') {
        console.log("Lấy icon biểu tượng web");
    } else if (req.url == '/') {
        res.writeHead(200, "OK", { 'Content-type': 'text/html' });
        res.write('Home', (err) => { console.log(err); }); res.end();
    } else {
        // đọc file bất kỳ theo tên file được truyền trên url
        // console.log(req.url); 
        // đọc file.VD: url = /a.html ==> req.url.substring(1) --> lấy tên file từ ký tự thứ 1 đến hết 
        fs.readFile(req.url.substring(1), (err, data) => {
            if (err) {
                // throw err res.writeHead(404,{'Content - type':'text / html'}); 
                return res.end();
            }; res.writeHead(200, "OK",
                { 'Content - type': 'text / html' });
            res.write(data.toString('utf8'))
            return res.end();
        })
    }
});
server.listen(80); console.log("server dang chay port 80");
Nguồn: zezo.dev