nodejs简单几行代码即可将目录发布成网站

const http = require('http')
const path = require('path')
const fs = require('fs')

const dir = 'D:/kb'

const server = http.createServer()

server.on('request', (req, res) => {
    let url = req.url
    let filePath = path.join(dir,'index.html')
    if (url !== '/') filePath = path.join(dir, url)

    console.log(filePath);

    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.setHeader('Content-Type','text/html;charset=utf8')
            return res.end(filePath + '不存在')
        }
        res.setHeader('Content-Type','text/html;charset=utf8')
        res.end(data)
    })
})

server.listen(3000, () => {
    console.log('server is running...');
})

 

你可能感兴趣的:(nodejs简单几行代码即可将目录发布成网站)