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

77 阅读2分钟

image.png

这是我参与「第四届青训营 」笔记创作活动的第11天

node.js的应用场景

  • 前端工程化
  • web服务端应用
  • electron跨端桌面应用

node.js运行时结构

特点

  1. 异步I/O
  • 会在响应返回后恢复操作,而不是阻塞线程并占用额外内存等待
  • 效率较高,系统复原利用率较高
  1. 单线程(js主线程)

JS线程+uv线程池+v8任务线程池+v8 Inspector线程

  1. 跨平台

编写Http Server

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

//返回json数据
const http = require('http')
const server = http.createServer((req, res) => {
    const bufs = []
    req.on('data', (buf) => {
        bufs.push(buf)
    })
    req.on('end', () => {
        const buf = Buffer.concat(bufs).toString('utf8')
        let msg = 'hello'
        try {
            const ret = JSON.parse(buf)
            msg = ret.msg
        } catch (err) {
            res.end('invalid json')
        }
        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)
})
——>改写promisify
const http = require('http')
const server = http.createServer(async (req, res) => {
    const msg = await new Promise((resolve, reject) => {
        const bufs = []
        req.on('data', (buf) => {
            bufs.push(buf)
        })
        req.on('error', (err) => {
            reject(err)
        })
        req.on('end', () => {
            const buf = Buffer.concat(bufs).toString('utf8')
            let msg = 'hello'
            try {
                const ret = JSON.parse(buf)
                msg = ret.msg
            } catch (err) {
                //res.end('invalid json')
            }
            resolve(msg)
        })
    })

    //response 
    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)
})



//http client  post请求
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)

静态文件服务器

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

const folderPath=path.resolve(__dirname,'./static')

const server=http.createServer((req,res)=>{
    const info=url.parse(req.url)
    //static/index.html
    const filepath=path.resolve(folderPath,'./',info.path)

    //stream api..
    const filestream=fs.createReadStream(filepath)
    filestream.pipe(res)
})

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

与高性能、可靠得服务相比,还差什么?

  1. CDN: 缓存+加速
  2. 分布式储存,容灾

React SSR 服务端渲染

特点

  1. 相比传统HTML模板引擎:避免重复编写代码
  2. 相比SPA:首屏渲染更快,SEO友好
  3. 缺点:通常qps较低,前端代码编写时需要考虑服务端渲染情况
  4. 难点
  • 需要处理打包代码
  • 需要思考前端代码在服务端运行时的逻辑
  • 移除对服务端无意义的副作用或重置环境

debug

v8 inspector

开箱即用、特性丰富强大、与前端开发一致、跨平台

  • node --inspect

场景

  • 查看console.log内容
  • breakpoint
  • 高CPU、死循环:cpuprofile
  • 高内存占用:heapsnapshot
  • 性能分析

部署

要解决的问题

  1. 守护进程:当进程退出时,重新拉起

  2. 多进程:cluster便捷地利用多进程

  3. 记录进程状态,用于诊断

  4. 容器环境 —— 通常有健康检查的手段,只需多考虑多核cpu利用率即可

延伸话题——node.js贡献代码