ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
ဒီ lesson က အသစ်သင်ဖို့မဟုတ်ဘဲ၊ Modules, fs Module, path Module, http Module သင်ခန်းစာတွေမှာ သင်ခဲ့တဲ့ concept တွေကို လက်တွေ့ code ရေးပြီး confirm လုပ်ဖို့ practice set ပါ။ File ဖန်တီးခြင်း၊ path တွေကို platform-independent ဖြစ်အောင် ဆက်တည်ဆောက်ခြင်း၊ ရိုးရှင်းတဲ့ HTTP server run ခြင်း သုံးမျိုးကို အသီးသီး လေ့ကျင့်ပါမယ်။ Task တစ်ခုချင်းစီကို editor ဖွင့်ပြီး node command နဲ့ run လုပ်ကြည့်ရင် fs, path, http module တွေ ဘယ်လိုအလုပ်လုပ်လဲဆိုတာ ပိုမိုရှင်းလင်းသွားပါလိမ့်မယ်။ Beginner level ဆိုပေမယ့် error handling ကိုပါ သတိထားရေးရပါမယ်။
လေ့ကျင့်ခန်းများ
Task 1: fs.writeFile သုံးပြီး todo.txt ဆိုတဲ့ file ကို string content နဲ့ ဖန်တီးပါ၊ ပြီးရင် fs.readFile နဲ့ ပြန်ဖတ်ပြီး console.log ထုတ်ပါ။ Task 2: path.join() နဲ့ folder နှစ်ခု (data, logs) ကို လမ်းကြောင်းတစ်ခုအဖြစ် ပေါင်းစပ်ပြီး path.basename() နဲ့ file name ကိုပဲ ခွဲထုတ်ပါ။ Task 3: http.createServer() နဲ့ port 4000 မှာ run မယ့် server တစ်ခုရေးပြီး, request URL က '/time' ဖြစ်ရင် လက်ရှိအချိန်ကို JSON အနေနဲ့ ပြန်ပေးပါ၊ တခြား URL ဆိုရင် 404 ပြန်ပေးပါ။ Task 4 (optional): Task 1 ရဲ့ file write/read logic ကို function တစ်ခုအဖြစ် ပြန်ရေးပြီး error ဖြစ်ရင် console.error နဲ့ ပြပါ။
Code နမူနာ
const fs = require('fs');
const path = require('path');
const http = require('http');
// Task 1: write + read a file
fs.writeFile('todo.txt', 'Learn Node.js modules\n', 'utf8', (err) => {
if (err) return console.error('Write failed:', err.message);
fs.readFile('todo.txt', 'utf8', (err2, data) => {
if (err2) return console.error('Read failed:', err2.message);
console.log('File content:', data);
});
});
// Task 2: path practice
const fullPath = path.join('data', 'logs', 'app.log');
console.log('Joined path:', fullPath);
console.log('Base name:', path.basename(fullPath));
// Task 3: mini http server
const server = http.createServer((req, res) => {
if (req.url === '/time') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ now: new Date().toISOString() }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(4000, () => console.log('Server running on port 4000'));todo.txt file ဖန်တီးပြီး content ကို terminal မှာ log ထုတ်ပြပြီး, http://localhost:4000/time ကို browser မှာဖွင့်ရင် current time ပါတဲ့ JSON ပြန်ပေးပါလိမ့်မယ်။၅ မိနစ် စမ်းကြည့်
5 minute အတွင်း Task 3 ကို ပြောင်းပြီး '/hello' route အသစ်တစ်ခု ထပ်ထည့်ကြည့်ပါ - request လာရင် '{ "message": "Hello Node.js" }' JSON ပြန်ပေးအောင် ရေးကြည့်ပါ။
သတိလေးတစ်ချက်
path module ကို string concatenation ('data' + '/' + 'logs') နဲ့ ကိုယ်တိုင်ဆက်တာထက် path.join() ကိုပဲ အမြဲသုံးပါ - Windows နဲ့ Linux slash character မတူလို့ bug ဖြစ်နိုင်ပါတယ်။