简单的文件夹浏览器源代码

2018-11-06  本文已影响0人  燃烧星星之火

let fs = require("fs");

let http = require("http");

let path = require("path");

let server = http.createServer((request, response) => {

    let url = request.url

    //过滤掉浏览器标签页的标签

    if (url == "/favicon.ico") {

        response.end("")

        return

    }

    console.log(url)

    let dir = "test"

    //这一步是关键

    if (url !== "/") {

        dir = "." + url

    }

    let fileNames = fs.readdirSync(dir);

    let htmlTag = ""

    fileNames.forEach(file => {

        let filepath = path.join(dir, file);

        let status = fs.statSync(filepath);

        if (status.isDirectory()) {

            htmlTag += "<tr><td><a href ='" + filepath + "'>" + file + "</td></tr>"

        } else {

            htmlTag += "<tr><td>" + file + "</td></tr>"

        }

    })

    response.end(makeHtml(htmlTag))

})

server.listen(8000)

function makeHtml(html) {

    return `<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="UTF-8">

        <title>Title</title>

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"

              integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    </head>

    <body>

        <table class="table table-hover">

            <tbody>

            ${html}

            </tbody>

        </table>

    </body>

</html>`

}

上一篇下一篇

猜你喜欢

热点阅读