Built-in Modules: fs, path, http, os

Built-in Modules คือโมดูลที่มาพร้อม Node.js โดยไม่ต้องติดตั้งเพิ่ม เช่น fs สำหรับไฟล์, path สำหรับจัดการ path, http สำหรับสร้าง Server และ os สำหรับอ่านข้อมูลระบบ

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุค Browser Sandbox / Browser JS"]
    A["ไม่มี fs/http server
เข้าถึงระบบจำกัด"] end subgraph Era2["ยุค Node Core / Built-in Modules"] B["fs/path/os
เข้าถึงระบบ"] C["http
สร้าง server ได้"] end subgraph Era3["ยุค Promise API / Modern Node"] D["fs.promises
async/await"] E["ES Modules
import syntax"] end A --> B --> C --> D --> E

โมดูลที่ใช้บ่อย

ตาราง Built-in Modules

Module หน้าที่ ตัวอย่าง Method
fs อ่าน/เขียนไฟล์ readFile, writeFile
path จัดการ path join, resolve
http สร้าง server createServer
os อ่านข้อมูลระบบ platform, cpus
process ข้อมูล process env, argv

Mermaid Diagram: File API Flow

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart TD
  A["Node App
โปรแกรม"] --> B["path.join
สร้าง path"] B --> C["fs.promises.readFile
อ่านไฟล์"] C --> D["JSON.parse
แปลงข้อมูล"] D --> E["HTTP Response
ส่งผลลัพธ์"]

Code Example

// built-in-demo.mjs
// ตัวอย่างใช้ fs, path, http, os และ process
import { readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import http from 'node:http';
import os from 'node:os';

const filePath = path.join(process.cwd(), 'message.txt');

// เขียนไฟล์แล้วอ่านกลับด้วย async/await
await writeFile(filePath, 'Hello from Node.js', 'utf8');
const message = await readFile(filePath, 'utf8');

console.log('Platform:', os.platform());
console.log('CPU cores:', os.cpus().length);
console.log('CLI args:', process.argv.slice(2));

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message }));
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

// ตัวอย่างการใช้งาน:
// node built-in-demo.mjs demo
// เปิด http://localhost:3000

กิจกรรมท้ายบท

กลับสัปดาห์ที่ 10