Node.js 以事件驅動非阻塞 I/O 模型,讓 JavaScript 走出瀏覽器成為服務端開發利器。本文演示 Ubuntu 下安裝 Node.js 後的兩個經典入門程式。
# Ubuntu 20.04+ sudo apt update && sudo apt install nodejs npm # 或使用 NodeSource 獲取最新 LTS curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - sudo apt install -y nodejs
建立 helloworld.js:
console.log("Hello world!");
執行:
node helloworld.js # 輸出:Hello world!
修改 helloworld.js:
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Hello World");
res.end();
});
server.listen(8888, () => {
console.log("Server running at https://localhost:8888/");
});
執行 node helloworld.js,瀏覽器訪問 https://localhost:8888/ 即見 "Hello World"。
require("http") 載入核心模組。createServer 回調函數接收 request(請求)、response(響應)物件。listen(8888) 綁定端口,啟動事件循環等待連接。這是 Node.js 微服務、API 網關、實時應用開發的起點。