使用node.js实现apache功能

先实现在url中输入文件路径能展示对应文件内容功能

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

const server = http.createServer()

const wwwDir = '/Users/lianglanlan/Desktop/code/study/node/www'

server.on('request', (req, res) => {
    const url = req.url

    let filePath = '/index.html'

    if (url !== '/') {
        filePath = url
    }
    fs.readFile(wwwDir + filePath, (err, data) => {
        if (err) {
            console.log(err)
            return res.end('404 Not Found')
        }
        res.end(data)
    })
})

server.listen(3010, () => {
    console.log('running...')
})

猜你喜欢

转载自www.cnblogs.com/lianglanlan/p/12196099.html