程式範例
下面兩題把前面學過的東西串在一起。請在自己的資料夾打一次並跑過,不要只看。
專案先準備:
在 package.json 加上 "type": "module"。
讀 JSON 並計算
scores.json:
average.js:
import { readFile } from "node:fs/promises";
const raw = await readFile("scores.json", "utf8");
const scores = JSON.parse(raw);
let total = 0;
for (const n of scores) {
total += n;
}
console.log("平均:", total / scores.length);
readFile 讀到的是文字;JSON.parse 把它轉成真正的陣列,才能用 for...of 相加。
預期輸出:平均: 85。用到:基礎型態、迴圈、檔案 IO、非同步。
依路徑回 JSON 的小伺服器
server.js:
import http from "node:http";
function json(response, data) {
response.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
response.end(JSON.stringify(data));
}
const server = http.createServer((request, response) => {
if (request.url === "/health") {
json(response, { ok: true });
return;
}
json(response, { message: "試試看 /health" });
});
server.listen(3000, () => {
console.log("http://127.0.0.1:3000/health");
});
JSON.stringify 把物件轉成文字,瀏覽器才看得懂 JSON。用瀏覽器開啟 http://127.0.0.1:3000/health,應看到 {"ok":true}。用到:函式、HTTP 伺服器。
自己再加一題
把第一題的讀檔與平均,接到第二題的伺服器:瀏覽器開 /average 時,回傳類似 {"average":85} 的 JSON。讀檔記得 await,路徑記得判斷 request.url。能做完,主線就落地了。