nodejs中express搭建本地web服务器

const express = require("express");

const fs = require("fs");

const path = require("path");

const app = express();

//读取当前目录中 public文件中所有文件
const directorPath = path.join(__dirname,"public");

app.get("/",(req,res)=>{
    fs.readdir(directorPath,(err,files)=>{
        if(err){
            return res.status(500),send("无法读取目录")
        }
        let content = "";
        //public 文件下所有目录列表
        files.forEach(item=>{
            content+=`<h2 onclick='window.location.href="/public/${item}"'>${item}</h2>`
        })
        res.send(content);
    })
})

app.use("/public",express.static("./public"));

app.listen(80,()=>{
    console.log("express server running at http://192.168.2.15")
})

 

posted @ 2024-05-21 17:55  波仔、  阅读(7)  评论(0编辑  收藏  举报