原生Node.js 实现http-server的思路是什么?

RT,越详细越好,谢谢大佬(可以有偿)

补充:不是简单地createServer,是仿照一个叫http-server的npm包,实现其功能,包括命令行:https://www.npmjs.com/package...

阅读 2.7k
1 个回答
// index.js
const http = require('http')
const fs = require('fs')
const path = require('path')

const types = {
  js: 'text/javascript',
  html: 'text/html',
  png: 'image/png',
  //...
}

const server = http.createServer((req, res) => {
  const url = req.url
  const currentPath = path.join(__dirname, url)
  if (!fs.existsSync(currentPath)) {
    res.end('no such file or directory')
    return
  }
  const stat = fs.statSync(currentPath)
  if (stat.isDirectory()) {
    const folder = fs.readdirSync(currentPath)

    const html = `
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <title>Document</title>
        </head>
        <body>
          <ul>
            ${folder
              .map(
                file => `
              <li>
                <a href="/${file}">${file}</a>
              </li>`,
              )
              .join('')}
          </ul>
        </body>
      </html>
    `

    res.end(html)
  } else {
    const extname = path.extname(url).replace('.', '')

    res.writeHead(200, {
      // 这里需要获取文件的`Content-Type`,我实现的比较糙,你可以自己优化一下,用第三方库,或者扩充一下 types
      'Content-Type': types[extname] || 'application/octet-stream',
      'Content-Length': stat.size,
    })
    const rs = fs.createReadStream(currentPath)
    rs.pipe(res)
  }
})

server.listen(8000)

运行node index.js然后访问http://localhost:8000查看效果

写了个大概的逻辑,具体细节你可以自己去补充.


撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题