Node.js与前端开发实战 | 青训营笔记

119 阅读2分钟

这是我参与【第五届青训营】笔记创作活动的第七天

2023.01.31

Node.js与前端开发实战

01.Node.js的应用场景(why)

  • 前端工程化
  • Web服务端应用
    • 学习曲线平缓,开发效率较高
    • 社区生态丰富及工具链成熟(npm,V8 inspector)
    • 与前端结合的场景会有优势(SSR)
  • Electron跨端桌面应用
    • 商业应用:vscode,slack,discord,zoom
    • 大型公司内的效率工具
  • Node.js在字节
    • BFF应用、SSR应用,举例:Modern.js
    • 服务端应用。举例:头条搜索,西瓜视频,懂车帝
    • Electron应用:飞书

02.Node.js运行时结构(what)

特点:

  • 异步I/O:当Node.js执行I/O操作时,会在响应返回后恢复操作,而不是阻塞线程并占用额外内存等待。
  • 单线程:
    • JS单线程:实际:JS线程+uv线程池+V8任务线程池+V8 Inspector线程
    • 优点:不用考虑多线程状态同步问题,也就不需要锁;同时还能比较高效地利用系统资源;
    • 缺点:阻塞会产生更多负面影响
    • 解决方法:多进程或多线程
  • 跨平台: 开发成本低,整体学习成本低

03.编写Http Server(how)

  • 目标:

    • 安装Node.js

      • Windows推荐nvm4w或是官方安装包
      • 安装慢,安装失败的情况,设置安装源
      • NVM_NODEJS_ORG_MIRROR=npmmirror.com/mirrors/nod… nvm install 16
    • 编写Http Server + Client,收发GET,POST请求

      • const http = require('http')
        
        const server = http.createServer((req,res) =>{
        	res.end('hello')
        })
        
        const port = 3000
        
        server.listen(port, () =>{
        	console.log('listening on: ',port)
        })
        

      const http = require('http')

      const server = http.createServer((req, res) => { const bufs = [] req.on('data', (buf) => { bufs.push(buf) }) req.on('end', () => { //bufs const buf = Buffer.concat(bufs).toString('utf8') let msg = 'hello'

            try {
                const ret = JSON.parse(buf)
                msg = ret.msg
            }catch (err) {
                //
            }
            
            const responseJson = {
                msg: `receive: ${msg}`        
            }
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify(responseJson))
        })
      

      })

      const port = 3000

      server.listen(port, () => { console.log('listening on: ', port) })

      
      - ```js
      //http_client
      
      const http = require('http')
      
      const body = JSON.stringify({
          msg:'Hello from my own client',
      })
      
      const req = http.request('http://127.0.0.1:3000', {
          method:'POST',
          headers:{
              'Content-Type': 'application/json',
          }
      },(res) => {
          const bufs = []
          res.on('data', (buf) => {
              bufs.push(buf)
          })
          res.on('end', () => {
              const buf = Buffer.concat(bufs)
              const json = JSON.parse(buf)
              
              console.log('json.msg is:', json.msg)
          })
      })
      
      req.end(body)
      
    • 编写静态文件服务器

    • 编写React SSR服务

      • SSR特点
        • 相比传统HTML模板引擎:避免重复编写代码
        • 相比SPA(single page application):首屏渲染更快,SEO友好
      • 缺点:
        • 通常qps较低,前端代码编写时需要考虑服务端渲染情况
    • 适用inspector进行调试、诊断

    • 部署简介