Dark mode
// วิธีที่แนะนำ import { readFile } from 'node:fs/promises'; import { createServer } from 'node:http'; import { join } from 'node:path';
// วิธีเก่า (ยังใช้ได้ แต่ไม่ชัดเจนเท่า) // import { readFile } from 'fs/promises';
## ภาพรวม Built-in Modules ที่สำคัญ
| ชื่อโมดูล | หน้าที่หลัก | ตัวอย่างการใช้ | หมายเหตุ |
| :--------------- | :--------------------------------------------------- | :--------------------------------- | :------------------------------------- |
| **`fs`** | จัดการไฟล์และไดเรกทอรี (อ่าน, เขียน, ลบ) | อ่าน/เขียนไฟล์, สร้างโฟลเดอร์ | ใช้ `fs/promises` สำหรับ Async/Await |
| **`path`** | จัดการเส้นทาง (Path) ข้ามแพลตฟอร์ม | รวม Path (`join`), แยกชื่อไฟล์ | สำคัญมากเมื่อทำงานกับไฟล์ |
| **`http`** | สร้าง HTTP Server และ Client | สร้าง API Server, เรียกเว็บ/API | พื้นฐาน Web App |
| **`https`** | `http` + การเข้ารหัส (SSL/TLS) | สร้าง HTTPS Server, เรียก API ปลอดภัย | ต้องใช้ Certificate |
| **`url`** | แยกส่วน (Parse) และจัดการ URL | ดึง Host, Path, Query Params | มี `URLSearchParams` ให้ใช้ |
| **`os`** | ให้ข้อมูลเกี่ยวกับระบบปฏิบัติการ (CPU, Memory) | ดูข้อมูลเครื่อง, หา Home Directory | ดูทรัพยากรระบบ |
| **`events`** | สร้างและจัดการ Event-driven programming | สร้าง Custom Events, จัดการ Async | หัวใจของ Non-blocking |
| **`stream`** | จัดการข้อมูลแบบไหลต่อเนื่อง (เหมาะกับข้อมูลใหญ่) | อ่านไฟล์ใหญ่, Network Stream | ประหยัด Memory |
| **`crypto`** | ฟังก์ชันเข้ารหัส (Hash, Encryption) | Hash รหัสผ่าน, เข้ารหัสข้อมูล | เพื่อความปลอดภัยข้อมูล |
| **`child_process`**| สร้างและควบคุมโปรเซสย่อย (รันคำสั่งอื่น) | รัน `git`, สคริปต์อื่น | ทำงานร่วมกับระบบ |
| **`timers`** | จัดการการหน่วงเวลา (`setTimeout`), ทำซ้ำ (`setInterval`) | ตั้งเวลา, ทำงานเป็นช่วงๆ | ใช้ `timers/promises` สำหรับ Async/Await |
| **`buffer`** | จัดการข้อมูล Binary (ข้อมูลดิบ) | รูปภาพ, Network Packets | เป็น Global Class |
## ตัวอย่างการใช้งานที่จำเป็น
::: details File System (`fs/promises`) & Path (`path`) - อ่านเขียนไฟล์
```javascript
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
async function main() {
const filePath = join(process.cwd(), 'data', 'log.txt');
try {
// สร้าง dir ถ้าไม่มี
await mkdir(join(process.cwd(), 'data'), { recursive: true });
// เขียนไฟล์
await writeFile(filePath, `Log entry: ${new Date()}\n`, { flag: 'a' }); // flag 'a' = append
console.log('Log appended to:', filePath);
// อ่านไฟล์
const content = await readFile(filePath, 'utf8');
console.log('File content:\n', content);
} catch (err) {
console.error('FS Error:', err);
}
}
main();
:::
HTTP (http
) - สร้าง Web Server ง่ายๆ
javascript
import { createServer } from "node:http";
const PORT = 3000;
const server = createServer((req, res) => {
console.log(`Request: ${req.method} ${req.url}`);
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello Node.js!");
} else if (req.url === "/about") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("About Us page");
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
URL (url
) - แยกส่วน URL
javascript
import { URL } from "node:url";
const urlString =
"https://example.com:8080/path/to/resource?query=value&id=123#section";
const myURL = new URL(urlString);
console.log("Protocol:", myURL.protocol); // https:
console.log("Hostname:", myURL.hostname); // example.com
console.log("Port:", myURL.port); // 8080
console.log("Pathname:", myURL.pathname); // /path/to/resource
console.log("Search (Query String):", myURL.search); // ?query=value&id=123
console.log("Hash:", myURL.hash); // #section
// ใช้ URLSearchParams จัดการ query
const params = myURL.searchParams;
console.log("Query Param (query):", params.get("query")); // value
console.log("Query Param (id):", params.get("id")); // 123
params.append("new", "param");
console.log("Updated Search:", params.toString()); // query=value&id=123&new=param
console.log("Updated URL:", myURL.toString());
Timers (timers/promises
) - รอแบบ Async/Await
javascript
import { setTimeout } from "node:timers/promises";
async function delayedAction() {
console.log("Starting delay...");
// รอ 2 วินาที
await setTimeout(2000);
console.log("...Delay finished!");
}
delayedAction();