昨天完成了一個簡單的資料處理小工具,可以讀 JSON → 篩選 → 輸出。
今天要把它優化成更完整的小專案:
我把計算平均分數的邏輯獨立放在 utils.js
,
主程式就專心處理「讀檔案、篩選、寫檔案」這些流程。
export function average(arr) {
let sum = arr.reduce((acc, n) => acc + n, 0);
return arr.length > 0 ? sum / arr.length : 0;
}
我希望可以在終端機這樣下指令:
node app.js input.json output.json 70
意思是:讀取 input.json
→ 篩選分數大於 70 → 輸出到 output.json
。
import fs from "fs";
import { average } from "./utils.js";
// 從 CLI 拿到參數
// node app.js input.json output.json 70
const [,, inputFile, outputFile, thresholdStr] = process.argv;
const threshold = parseInt(thresholdStr, 10);
// 讀取 input.json
let rawData = fs.readFileSync(inputFile, "utf-8");
let students = JSON.parse(rawData);
// 篩選分數 > threshold 的學生
let passed = students.filter(s => s.score > threshold);
// 計算平均分數
let avgScore = average(students.map(s => s.score));
// 輸出結果到 output.json
fs.writeFileSync(outputFile, JSON.stringify(passed, null, 2));
console.log(`已將分數 > ${threshold} 的學生輸出到 ${outputFile}`);
console.log("全班平均分數:", avgScore);
最後幫這個小工具補一份 README
,假設有其他人要用,也能快速上手。
資料處理小工具
一個簡單的 Node.js CLI 工具,可以讀取 JSON 學生名單,篩選分數高於指定門檻的人,並輸出新的檔案。
使用方式
安裝依賴:
npm install
執行程式:
node app.js input.json output.json 70
說明:
input.json
:輸入檔案output.json
:輸出檔案70
:篩選條件,分數必須大於這個數字範例
假設 input.json:
[ { "name": "小明", "score": 80 }, { "name": "小美", "score": 55 }, { "name": "阿土", "score": 90 } ]
執行:
node app.js input.json passed.json 70
輸出 passed.json:
[ { "name": "小明", "score": 80 }, { "name": "阿土", "score": 90 } ]
今天最大的成就感就是:這個小工具不只是「能跑」,還能用參數控制輸入與輸出,算是比較完整的程式了。
這幾天的過程讓我體會到: