这是我参与「第五届青训营 」伴学笔记创作活动的第 7 天
一、本堂课重点内容:
- Node.js的应用场景(why)
- Node.js运行时结构(what)
- 编写Http Server (how)
二、详细知识点介绍:
Node.js的应用场景(why)
- 前端工程化
- web服务端应用
- Electron跨端桌面应用
Node.js运行时结构(what)
- V8、libuv
- V8:JavaScript Runtime,诊断调试工具 (inspector)
- libuv: eventloop(事件循环), syscall(系统调用)
- 举例:用node-fetch 发起请求时...
- node.js运行特点
- 异步O/I:当Node.js执行I/O操作时,会在响应返回后恢复操作,而不是阻塞线程并占用额外内存等待
- 单线程:优点是不用考虑多线程状态同步问题,也就不需要锁;同时还能比较高效地利用系统资源;缺点是阻塞会产生更多负面影响,解决办法是多进程或多线程
- 跨平台
编写Http Server (how)
- Debug
- V8 lnspector: 开箱即用、特性丰富强大、与前端开发一致、跨平台
- node --inspect
- open http://localhost:9229/json
- 场景:
- 查看console.log内容
- breakpoint
- 高CPU、死循环: cpuprofile
- 高内存占用: heapsnapshot
- 性能分析
- 部署要解决的问题
- 守护进程:当进程退出时,重新拉起
- 多进程:cluster便捷地利用多进程
- 记录进程状态,用于诊断
- 容器环境
- 通常有健康检查的手段,只需考虑多核cpu利用率即可
三、实践练习例子:
http Server搭建
const http = require('http')
const server = http.createServer((req, res) => {
res.end('hello')
})
const port = 3000
server.listen(port, () => {
console.log('listen on:', port);
})
http server json
const http = require('http')
const { json } = require('stream/consumers')
const server = http.createServer((req, res) => {
const bufs = []
req.on('data', (buf) => {
bufs.push(buf)
})
req.on('end', () => {
const buf = Buffer.concat(bufs).toString('utf-8')
let msg = 'hello'
try {
const ret = JSON.parse(buf)
const msg = ret.msg
} catch (err) {
}
const responseJson = {
msg: `receive:${msg}`
}
res.setHeader('Contenet-Type', 'application/json')
res.end(JSON.stringify(responseJson))
})
})
const port = 3000
server.listen(port, () => {
console.log('listen on:', port);
})
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).toString()
const json = JSON.parse(buf)
console.log('json.msg is :', json.msg)
})
})
req.end(body)
四、课后个人总结:
这次课程是关于node.js的指导性课,技术学习还需要观看官方文档