跳轉到

1.3 第一支程式與模組系統#

你的第一支 Node 程式#

建立 hello.js:

console.log("Hello, Node!");

執行:

node hello.js
# Hello, Node!

也可以用互動模式(REPL)直接玩:

node
> 1 + 1
3
> .exit    # 離開

模組系統:把程式拆成檔案#

程式大了就要拆檔案。Node 有兩套模組系統:

CommonJS(傳統,舊專案常見)#

// math.js —— 匯出
function add(a, b) {
  return a + b;
}
module.exports = { add };
// app.js —— 匯入
const { add } = require("./math");
console.log(add(1, 2)); // 3

ESM(現代標準,新專案建議用)#

先在 package.json 加上 "type": "module",然後:

// math.js —— 匯出
export function add(a, b) {
  return a + b;
}
// app.js —— 匯入
import { add } from "./math.js";
console.log(add(1, 2)); // 3

兩套怎麼選?#

CommonJS ESM
匯出 module.exports export
匯入 require() import ... from
支援 所有舊版 Node 與舊套件 Node 12+,現代標準
建議 維護舊專案時用 新專案優先

記憶法:路徑要寫清楚——require("./math") 可以省略副檔名,但 ESM 的 import 建議寫完整的 "./math.js"。

節點內建模組:不用安裝就能用#

Node 自帶許多模組,直接 require / import 就能用,不用 npm 安裝:

const fs = require("node:fs");       // 讀寫檔案
const path = require("node:path");   // 處理路徑
const http = require("node:http");   // 建立 HTTP 伺服器

加上 node: 前綴是現代建議的寫法,明確表示這是內建模組,不是 npm 套件。下一章會介紹常用的幾個。