原生Web Server的实战

1、Web Server的构成

2、Nodejs作为Web Server的优势

3、Web Server最小系统

 Web Server的构成 

处理HTTP 对HTTP的动词(get、post、put)进行响应
路由管理 分别处理不同URL路径的请求,返回对应的网络资源
静态文件托管 对网络请求的静态资源进行响应或使用动态模板响应请求
文件数据存储 将请求携带的数据存储到文件或者数据库中

Web Server的基本架构

  服务器和数据库中间增加其他的服务,

 Nodejs作为Web Server的优势 

1、并发性能优异 基于事件驱动的服务在响应请求的场景中有极高的并发性能表现
2、js同构 减少学习成本,使用最流行的js或者其他可编译/转换为js的语言均可实现
3、生态活跃完善 npm提供了数十万个可重用的工具包,还挺乖了一六的依赖解决方案,可实现自动化工具链构建
4、代码可移植 兼容各种操作系统运行环境,一份代码可以运行在多种环境中
5、框架高度包容 Node及Node的Web框架都拥有天然的包容性,易于拓展和维护
6、友好的社区氛围 丰富的生态诞生了大量的开源社区,聚集了众多优秀的开发人员
/**
 * 创建服务
 * 1、加载http模块
 * 2、创建http服务
 * 3、监听事件请求
 * 4、监听端口,请开启服务
 * 分发路由
 *  根据req的url属性判断路由信息
 * 
 */

const http = require('http')
const server = http.createServer()

server.on('request', (req, res) => {
  /**
   * 监听到请求所做的操作
   * req对象,包含用户请报文的所有内容,可以通过req获取用户提交过来的数据
   * res对象,用来响应数据,服务器想要向客户端相应数据的时候使用该对应
   */
  res.setHeader('Content-Type', 'text/html;charset=utf-8')
  if(req.url === '/' || req.url === '/index') {
    res.write('<h1>Hello Index !!!</h1>')
  } else if(req.url === '/list'){
    res.write('<h3>list....</h3>')
  } else {
    res.write('<h3>404....</h3>')
  }
  res.end()
})

server.listen('3000', () => {
  console.log('Node服务运行在3000')
})
/**
 * 创建服务
 * 1、加载http模块
 * 2、创建http服务
 * 3、监听事件请求
 * 4、监听端口,请开启服务
 * 分发路由
 *  根据req的url属性判断路由信息
 * 根据不同请求,享有哦现有的html文件
 */
const path = require('path')
const fs = require('fs')
const http = require('http')

http.createServer((req, res) => {
  if(req.url === '/' || req.url === '/index') {
    fs.readFile(path.join(__dirname, 'htmls','index.html'), (err, data) => {
      if(err) throw err
      res.end(data)
    })
  } else if(req.url === '/list'){
    fs.readFile(path.join(__dirname, 'htmls','list.html'), (err, data) => {
      if(err) throw err
      res.end(data)
    })
  } else {
    fs.readFile(path.join(__dirname, 'htmls','404.html'), (err, data) => {
      if(err) throw err
      res.end(data)
    })
  }
}).listen(3000, () => {
  console.log('Node服务运行在3000')
})

Web Server最小系统 

  nodemon 用来监控 node.js 源代码的变化和自动重启服务器 (npm 安装)

  HTTPie 用于与 HTTP 服务器做测试、调试和常规交互

const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
const qs = require('querystring')

const notFound = (req, res) => {
  fs.readFile(path.join(__dirname, '404.html'), (err, data) => {
    if(err) {
      res.write(404, 'not found')
    }else {
      res.writeHead(404, {'Content-type': "text/html;charset='utf-8'"})
      res.write(data)
      res.end()
    }
  })
}
const writeDb = (chunk) => {
  fs.appendFile(path.join(__dirname, 'db'), chunk, err => {
    if(err) throw err
    console.log('db insert...', chunk && chunk.toString())
  })
}

http.createServer((req, res) => {
  // 1、路由处理
  // 2、静态资源托管
  // 3、HTTP verb
  // 4、持久化数据 store
  let pathName = url.parse(req.url).pathname // 路径解析

  // /api => 接口
  if(pathName.startsWith('/api')) {
    const method = req.method
    if(method === 'GET') {  
      const query = qs.parse(url.parse(req.url).query) //?a=1&b=2
      const resData = {
        code: 200,
        msg: 'success',
        data: query
      }
      res.end(JSON.stringify(resData))
      return
    }
    if(method === 'POST') { // HTTPie
      const contentType = req.headers('content-type')
      if (contentType === 'application/json') {
        let postData = ''
        req.on('data', chunk => {
          postData +=  chunk
          writeDb(postData)
        })
        req.on('end', () => {
          res.end(postData)
        })
      }
    }
  }

  if(pathName === '/') {
    pathName = path.join(__dirname, 'index.html')
  }
  const extName = path.extname(pathName)  // 取后缀名

  if(extName === '.html') {
    // index.html 文件读取模块
    fs.readFile(pathName, (err, data) => { // data为Buffer
      if(err) {
        // 404
        notFound(req, res)
      }else {
        res.writeHead(200, {'Content-Type': "text/html;charset='utf-8'"})
        res.write(data)
        res.end()
      }
    })
  }

  // res.write('hello Nodejs 1')
  // res.end()
}).listen(8080)

// 改变内容需要频繁启动 引入第三方插件 nodemon 监听代码变更 npm安装
原文地址:https://www.cnblogs.com/slightFly/p/13894475.html