Node.js| 青训营笔记

41 阅读2分钟

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

本堂课重点内容

1. 介绍 Node.js 的应用场景 2. 介绍 Node.js 运行时结构 3. 如何用编写 Http Server 4. 延伸话题

重点知识点介绍

nodejs运行时结构

image-1674996797002.png

特点:

1. 异步IO

当Node.js执行IO操作时,会在响应返回后恢复操作,而不是阻塞线程并占用额外内存等待

image-1674996944899-1674999453046.png 2. 单线程

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

优点:不用考虑多线程状态同步问题,也就不需要锁,同时还能比较高效的利用系统资源

缺点:阻塞会产生更多负面影响,一般使用多线程或多进程解决

3. 跨平台

Node.js跨平台+JS无需编译环境+Web跨平台+诊断工具跨平台

==>开发成本低,整体学习成本低

编写Http Server
const http = require('http')

const port = 3000

const server = http.createServer((req, res) =>{
    res.end('Hello Node.js')
})

server.listen(port, () => {
    console.log(`server listens on: ${port}`)
})
// 这是可以发送文本消息的服务器

http.createServer 会返回 server 的对象

创建 Server 时会传入一个回调函数,这个回调函数在被调用时会传入两个参数:

- req:request请求对象,包含请求相关的信息

- res:response响应对象,包含我们要发送给客户端的信息

- ##### 编写Http Client

listen(主机host,(端口port),回调函数)

// http client
const http = require('http');

const body = JSON.stringify({
    msg: 'Hello World'
});

const req = http.request(
    'http://localhost:3000',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': body.length,
        },
    }, (res) => {
        const buffer = [];
        res.on('data', (chunk) => {
            buffer.push(chunk);
        })
        res.on('end', () => {
            const receive = JSON.parse(Buffer.concat(buffer).toString())
            console.log(receive);
        })
    }
);

req.end(body);
Debug

可以使用V8 Inspector,应用场景有

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

课后个人总结

这节课老师讲了关于Node.js的简单运用,收获最大的一点是知道了V8 Inspector强大功能。之前项目报错或者运行状况不佳都是从头开始code review,费时费力。

引用参考

‌‍⁣‌⁣‬‍⁢⁡⁤⁡‍⁤⁡⁡⁣‍⁤⁣⁢‬⁤‌‬‌‌‍‌⁤‬⁢⁡‌⁢‬Node.js 与前端开发实战