使用node.js实现apache功能

Posted 懒懒同学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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.htmlif (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...‘)
})

以上是关于使用node.js实现apache功能的主要内容,如果未能解决你的问题,请参考以下文章