静态服务器 Static Server

262 阅读1分钟

静态网络服务器(static web server)

由一个计算机(硬件)和一个 HTTP 服务器(软件)组成
我们称它为 “静态” 是因为这个服务器把它托管文件的 “保持原样”地传送到你的浏览器
自动查找对应文件,即静态文件服务器

服务器代码

var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if (!port) {
  console.log('请指定端口号好不啦?\nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function (request, response) {
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url
  var queryString = ''
  if (pathWithQuery.indexOf('?') >= 0) { queryString
      =pathWithQuery.substring(pathWithQuery.indexOf('?'))
  }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method
  
  console.log('有个二哈发请求过来啦!路径(带查询参数)为:' + pathWithQuery)

  response.statusCode = 200
  const filePath = path === '/' ? '/index.html' : path
  const index = filePath.lastIndexOf('.')
  const suffix = filePath.substring(index)
  const fileTypes = {
    '.html': 'text/html',
    '.css': 'text/css',
    '.js': 'text/javascript',
    '.png': 'image/png',
    '.img': 'image/jpeg'
  }
  response.setHeader('Content-type', `${fileTypes[suffix] 
  || 'text/html'};charset=utf-8`)

  let content
  try {
    content = fs.readFileSync(`./public${filePath}`)
  } catch (error) {
      content = '文件不存在'
      response.statusCode = 404
    }
  response.write(content)
  response.end()
})

server.listen(port)
console.log('监听 ' + port + ' 成功\n请打开 http://localhost:' + port)

详细资料点击:网络服务器