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

38 阅读2分钟

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

Node.js

前端工程化

Bundle: webpack vite esbuild parcel Uglify: Uglify.js Transpile: bable ts 其他语言:esbuild parcel prisma

Web服务端应用:

学习曲线平缓,开发效率较高,与前端结合的场景会有优势(SSR)。

Electron跨端:

vscode discord

应用:

BFF层,SSR应用 :Modern.js

Node.js运行时结构:

V8引擎,调试工具node-inspector libuv: eventloop, syscall

运行时结构的特点:

异步IO:当Node,js 执行IO操作时,会在响应返回后恢复操作,而不是阻塞线程,这样会避免一些额外的内存占用。 单线程: JS线程 + uv线程池 + V8任务线程池 + V8 inspector 线程(调试) 优点就是不用考虑多线程状态同步问题,也就是不需要锁,同时还能高效利用系统资源。 但是随之而来的阻塞线程所带来的一些负面影响(延时敏感)。 跨平台: Node.js + JS无需编译环境。 优点就是开发成本较低,整体的学习成本较低。

Node.js版本管理

nvm管理,使用NVM可以非常方便的切换Node.js的版本。

Http-Server编写

const http = require("http");
​
const server = http.createServer((req, resp) => {
  resp.end("hello");
});
​
const port = 2000;
​
server.listen(port, () => {
  console.log("server listen:", port);
});

实现返回一个JSON

const http = require("http");
​
const server = http.createServer((req, resp) => {
  const bufs = [];
  req.on("data", (buf) => {
    bufs.push(buf);
  });
  req.on("end", () => {
    const buff = Buffer.concat(bufs).toString("utf-8");
    try {
      const ret = JSON.parse(buff);
      const msg = ret.msg || "hello";
      const responseJson = {
        msg: `receive:${msg}`,
      };
      resp.setHeader("Content-Type", "application/json");
      resp.end(JSON.stringify(responseJson));
    } catch (error) {
      resp.end("invaild json");
    }
  });
});
​
const port = 2000;
​
server.listen(port, () => {
  console.log("server listen:", port);
});
client
const http = require("http");
​
const body = JSON.stringify({
  msg: "This is a message from client",
});
​
const req = http.request(
  "http://localhost:2000",
  {
    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);
    });
  }
);
​
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, resp) => {
  const info = url.parse(req.url);
​
  const filePath = path.resolve(folderpath, info.path);
  const fileStream = fs.createReadStream(filePath);
​
  fileStream.pipe(resp);
});
​
const port = 3000;
​
server.listen(port, () => {
  console.log("listening: ", port);
});

SSR

特点

避免了重复编写代码 相比SPA,首屏渲染更快,SEO友好

缺点

qps更低,前端代码编写时要考虑服务器资源

Inspector

开箱即用,跨平台。 查看console.log,断点,高CPU,死循环,高内存占用,性能分析。