1. 程式人生 > >Simple usage of module http in Node.js

Simple usage of module http in Node.js

Server side

const http=require("http")
const server=http.createServer((req,res) => {
    if (req.url=="/favicon.ico") {
        res.end()
        return
    }
    showdir(req,res)
})
server.listen(8000)
const path=require("path")
const fs=require("fs")
const util=require("util")
const showdir=async (req,res) => {
    const files=await util.promisify(fs.readdir)(path.join(__dirname,req.url))
    let lis=""
    for (let i=0;i<files.length;i++) {
        const fileinfo=await util.promisify(fs.stat)(path.join(__dirname,req.url,files[i]))
        if (fileinfo.isDirectory()) {
            const p=path.join(req.url,files[i])
            lis+=`<li><a href="${p}">${files[i]}</a></li>`
        } else {
            lis+=`<li>${files[i]}</li>`
        }
    }
    res.writeHead(200,{"Content-type":"text/html;charset=utf-8"})
    res.end(makehtml(lis))
}
const makehtml=lis => {
    return `
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8"> <title>     </title> <style>
            *{padding:0;margin:0}
            ul{
            padding: 15px;
            background-color:#eee;
            }
    ul>li{
        list-style: none;
                padding: 10px;
                background-color:#eee;
                transition: all 1s;
    } li:hover{
                background-color:#aaa;
            }
            li:not(:first-child){
                border-top: 1px solid #ccc;
    }
        </style>
    </head>
    <body>
    <ul>${lis}</ul>
    </body>
    </html>
    `
}

Client side

const http=require("http")
http.get("http://www.szhgh.com",res => {
    let data=""
    res.on("data",d => {
        data+=d
    })
    res.on("end",() => {
        console.log(data)
    })
})