Built-in Modules คือโมดูลที่มาพร้อม Node.js โดยไม่ต้องติดตั้งเพิ่ม เช่น fs สำหรับไฟล์, path สำหรับจัดการ path, http สำหรับสร้าง Server และ os สำหรับอ่านข้อมูลระบบ
%%{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
fs.readFile() อ่านไฟล์แบบ callbackfs.writeFile() เขียนไฟล์fs.existsSync() ตรวจว่าไฟล์มีอยู่หรือไม่fs.promises.readFile() อ่านไฟล์แบบ async/awaitpath.join() รวม path แบบข้าม OS ได้path.resolve() แปลงเป็น absolute pathpath.extname() อ่านนามสกุลไฟล์http.createServer() สร้าง HTTP Server เองos.platform(), os.cpus(), os.totalmem(), os.freemem() อ่านข้อมูลเครื่องprocess.env, process.argv, process.exit() อ่าน environment, argument และออกจาก process| Module | หน้าที่ | ตัวอย่าง Method |
|---|---|---|
fs |
อ่าน/เขียนไฟล์ | readFile, writeFile |
path |
จัดการ path | join, resolve |
http |
สร้าง server | createServer |
os |
อ่านข้อมูลระบบ | platform, cpus |
process |
ข้อมูล process | env, argv |
%%{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
ส่งผลลัพธ์"]
// 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
message.txt ด้วย fs.promises.writeFilehttp.createServeros.platform() และจำนวน CPU cores ใน console