萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Ubuntu Node.js 入門:從控制台 Hello World 到 HTTP 服務器

Node.js 以事件驅動非阻塞 I/O 模型,讓 JavaScript 走出瀏覽器成為服務端開發利器。本文演示 Ubuntu 下安裝 Node.js 後的兩個經典入門程式。

前置:安裝 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

程式 1:控制台輸出

建立 helloworld.js:

console.log("Hello world!");

執行:

node helloworld.js
# 輸出:Hello world!

程式 2:HTTP 服務器(Web 版 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 網關、實時應用開發的起點。

copyright © 萬盛學電腦網 all rights reserved