今天想來談談 Node.js 內建模組概念
其實雖然很多公司都說這個職位是前端,但有的時候根本也要自己會寫一些後端
(就是領著前端的薪水還要會寫後端 XD)
與其這樣不如技能都掌握起來~一定都能用上(也很感謝身在有 AI 的時代呀~)
可以把 Node.js 內建模組(Built-in Modules) 理解成:
Node.js 安裝好就附送的一組工具,不需要另外 npm install。
先用前端角度理解
一個 React 專案可能會:import _ from "lodash";
lodash 是第三方套件,所以要先:npm install lodash
但 Node.js 有很多功能是本身就提供的,例如:
const fs = require("fs");
const path = require("path");
const os = require("os");
這些就是 Node.js 的內建模組,不用 npm install fs
常見的 Node.js 內建模組
| 模組 | 用途 | 可以想成 |
|---|---|---|
fs |
操作檔案 | 讀檔、寫檔、刪檔 |
path |
處理路徑 | 組合 /src/config/file.js |
os |
取得作業系統資訊 | CPU、記憶體、系統資訊 |
http |
建立 HTTP Server | 自己做一個簡單 Web Server |
https |
HTTPS 功能 | 加密版 HTTP |
url |
處理 URL | 拆解網址 |
events |
事件機制 | 監聽 / 觸發事件 |
crypto |
加密相關 | hash、亂數等 |
stream |
串流資料 | 大檔案分批處理 |
1.fs:File System
例如讀取一個 JSON:
const fs = require("fs");
const data = fs.readFileSync("./config.json", "utf8");
console.log(data);
意思就是:
Node.js
↓
使用 fs
↓
讀取電腦上的 config.json
這種功能瀏覽器裡的 JavaScript 通常不能直接隨便做,但 Node.js 可以。
2.path:處理檔案路徑
例如:
const path = require("path");
const filePath = path.join("src", "config", "app.js");
console.log(filePath);
可能得到:src/config/app.js
它的價值是幫你安全地組合 Windows、Linux、macOS 的路徑。
3.http:建立 Web Server
Node.js 甚至不需要 Express 就能自己建立 Server:
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello World");
});
server.listen(3000);
執行:node server.js
然後瀏覽器連到:localhost:3000
就可以收到:Hello World
跟 Express 的差別其實可以理解成:
Node.js
│
├── 內建 http 模組
│ ↓
│ 可以建立 Server
│
└── Express(第三方套件)
↓
把建立 API / Server
這件事情變得更方便
例如 Node 原生:const http = require("http");
Express 則是:const express = require("express");
差別在於:
http → Node.js 內建 → 不用 npm install
express → 第三方套件 → npm install express
所以 Node.js 內建模組 = Node.js 原廠已經幫你準備好的 JS 工具箱。