这是我参与「第五届青训营 」伴学笔记创作活动的第 10 天
Node.js
编写 Http Server
例子 server的hello world 代码
const http =require('http')
const port = 3000
const server =http.createServer((req,res) => {
res.end('hello')
})
server.listen(port,()=> {
console.log('server listens on ${port}')
})
可以收到用户传给的数据hello
const http = require('http')
const port = 3000
const server = http.createServer((req,res) => {
const bufs =[]
req.on('data', data => {
bufs.push(data)
})
req.on('end', () => {
let reqDate ={}
try{
reqData =JSON.parse(Buffer.concat(bufs).toString)
}catch(err){
//receive invalid json data
}
res.setHeader('Content-Type' ,'application/json')
res.end(JSON.stringify({
echo: reqData.msg || 'Hello',
}))
})
})
修改代码,代码里面用了很多回调函数,代码的维护变得不是很方便。为了使得代码更好,可以用Promise+async await可以重写代码,技巧就是将callback转换为promise。不是所有的回调函数都可以改,promise只适合回调一次的
function wait(t){
return new Promise((resolve, reject) =>{
setTimeout(() => {
resolve()
},t)
})
}
编写简单的静态文件服务
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)
console.log('filepath',filepath)
//stream api
const filestream = fs.createReadStream(filepath)
filestream.pipe(res) //stream 风格的API,内部做了处理,可以帮助占用尽可能少的内存空间
})
const port = 3000
server.listen(port,() => {
console.log('listening on:', port)
})
与高性能、可靠的服务相比,还需要:
- CDN:缓存+加速
- 分布式存储,容灾
SSR(server side rendering)的特点
- 相比传统HTML模板引擎,避免重复编写代码
- 相比SPA(single page application):首页渲染更快,SEO友好
缺点 - 通常qps(每秒查询率)比较低,前端代码编写的适合需要考虑服务端渲染的情况
替换React后的代码
const React =require('react')
const ReactDOMServer =require('react-dom/server')
const http = require('http')
function App(props) {
//return <div>hello</div>
return React.createElement('div',{}, props.children || 'hello')
}
const port = 3000
const server =http.createServer((req,res) => {
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
${ReactDOMServer.renderToString(React.createElement(App, {} ,'my_content'))}
</body>
</html>
`)
})
server.listen(port,()=> {
console.log('server listens on ${port}')
})
SSR的难点
- 需要打包处理代码
- 需要思考前端代码在服务端运行时的逻辑
- 移除对服务端无意义的副作用,或者重置环境
Debud调试工具
- V8 Inspector:开箱即用,特性丰富强大,与前端开发一致,跨平台
- node --inspect
- open http://localhost:9229/json
- 场景
- 查看console.log内容
- breakpoint
- 高CPU、死循环:cpuprofile
- 高内存占用:heapsnapshot
- 性能分析
部署
- 部署需要解决的问题(本地开发完应用之后需要部署)
- 守护进程:当进程退出的时候,重新拉起。记录了进程的状态,启动进程
- 多进程:cluster便捷地利用多进程
- 记录进程状态,用于诊断
- 容器环境 通常由健康检查地手段,只需要考虑多核CPU利用率
延申话题
-
Node.js 贡献代码 快速了解Node.js代码 Node.js Core贡献入门
-
编译Node.js 如何编译:参考:
- Maintaining the build files
- ./configure && make install
- 演示:给net模块添加自定义属性
-
诊断/追踪
-
WASM,NAPI
- Node.js(V8)是执行WASM代码的天然容器,和浏览器WASM是同一运行时,同时Node.js支持WASI
- NAPI执行C接口的代码(c/c++/Rust……),同时保留原生代码的性能
- 不同的编程语言间通信的一种方向