11. Node.js与前端开发实战

87 阅读1分钟

1. Node.js的应用场景

  • 前端工程化 如webpack,bablejs,Typescript

  • Web服务端应用

    • 开发效率高
    • 不需要编译,运行效率高
    • 工具链成熟(npm)
    • 与前端结合的场景会有优势
  • Electron跨端桌面应用

    • 商业应用:vscode,slack,discord,zoom

2. Node.js的运行时结构

  • V8: JavaScript Runtime
  • libuv: eventloop(事件循环)

nodejs特点

  1. 异步I/O 执行I/O操作时,会在响应返回后恢复操作,而不是阻塞线程

  2. 单线程

    • 实际:JS线程 + uv线程池 + V8任务线程池

    • 优点: 不用考虑多线程状态同步问题,也就不需要锁

    • 缺点:阻塞会产生更多负面影响

      • 解决方法:多进程或多进程
  3. 跨平台

3. 编写Http Server

// 1、简单的服务器创建

let http = require("http")
const server = http.createServer(function (request, response) {

    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, { 'Content-Type': 'text/plain' });

    // 发送响应数据 "Hello World"
    response.end('Hello World\n');
})

const port = 8888
server.listen(port, () => {
    // 终端打印如下信息
    console.log('Server running at http://127.0.0.1:8888/');
})