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

发布于 2022-09-13 00:32:28 字数 192 浏览 21 评论 0

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花海 2022-09-20 00:32:28
// 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查看效果

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


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文