NodeJS知识小总结

172 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

1. NodeJS三大特性:

  1. 非阻塞IO
  2. 单线程
  3. 事件驱动

2. 非阻塞IO的理解:

  1. IO: input / output 输入 / 输出
  2. 阻塞IO(C语言): 前一个IO没完事,程序接着等 -- 同步
  3. 非阻塞IO(Java, Node): 前一个IO没完事,程序接着跑 -- 异步

3. 常用NodeJS模块

  1. http
    1. HTTP/HTTP2
    2. HTTPS
  2. assert - 断言
  3. Buffer - 二进制
    1. File ystem - 文件系统
  4. c++插件
  5. 多进程
  6. child_process - 子进程
  7. cluster - 集群
  8. process - 进程
  9. crypto - 加密( md5, sha )
  10. OS - 操作系统
  11. Path- 路径
  12. Events - 事件队列
  13. Query String - 查询字符串
  14. 网络
    1. TCP - 稳定 Net模块
    2. UDP - 快 UDP/ Datapgram模块
  15. DNS/domain - 域名服务器/ 域 ( 域名解析 )
  16. Sream - 流操作
    1. 连续性数据操作都是流 ---视频流, 网络流,文件流,语音流
  17. TLS/SSL- 加密,安全
  18. ZLIB - 压缩

4. express使用

  • express非破坏性结构框架,能使用原生nodejs
  • 中间件 - 插件
  • get,post, use - 通用
res.send(数据)             // res.send({name:"asdas"})
res.sendFile(绝对路径)     // res.sendFile(pathlib.resolve("a.txt")))
res.sendStatus(状态码)     // res.sendStatus(404)
res.redirect(重定向地址)   // res.redirect("http://www.baidu.com")
  • get -- req.query
  • 普通post
server.use(bodyParser.urlencoded({ extended: false })) --> req.body
  • 文件post
server.use(multer({ dest: "./upload/" }).any()) --> req.body req.files
  • cookie -- 存在浏览器里,容量4KB
  • session -- 存在服务器里,
  • session防止挟持
  • 1.定期更换session ID,有一定期限
  • 2.签名
server.use(cookieParser("asdasdaishdahsfhwqhfihasfhaskhfkaswihkalads")) // [可选]

req.cookies                           // 接收
req.signedCookies                     // 接收带签名值,自动验证签名值串改,{ccc: false}
res.cookies(key, val, options)        // 发送
res.cookies(key, val, {signed: true}) // 发送带有签名值

server.use(cookieSession({
  keys: ["adssadasd", "rwfsfadasd", "asdasfwra", "fasfasfsa"] // 循环使用
  //, secret:"asdasdas"
}))

req.session

4.1 路由与传参

// 路由 优点:路由,利于SEO
/article/:id
req.params

// 传参 优点:灵活
/article?id=161664
req,jquery

/article/:a/:b/:c/
/article?a=xxx&c=xxx

4.2 后台模板引擎

  • pug - 破坏式(破坏HTML结构)
  • 缩进显示层级
  • ejs - 非破坏式(保留HTML结构)
<%  %>
<%= %>
<%- %>
<% include("")%>