กลับไปหน้าบทความ

🟢 Node.js (สอนแบบครบระดับ)

Node.js คือ JavaScript runtime ฝั่งเซิร์ฟเวอร์ เหมาะกับงาน API, realtime, และงานที่ต้องการ I/O จำนวนมาก

📋 เนื้อหา (พื้นฐาน)

  • 🧭 Node.js คืออะไร
  • ⚙️ ติดตั้ง & npm
  • 📦 Modules
  • ⏳ Async พื้นฐาน
  • 🏁 สรุป
  • 📝 แบบฝึกหัด

🧭 Node.js คืออะไร

ทำไมต้อง Node.js?

Node.js คือ JavaScript runtime ที่สร้างบน Chrome V8 engine ทำให้รัน JavaScript บนเซิร์ฟเวอร์ได้ มีจุดเด่นคือ non-blocking I/O และ event-driven architecture

  • • เร็วและ scalable: Event-driven, non-blocking I/O
  • • ใช้ JS ทั้ง frontend และ backend: Full-stack JavaScript
  • • Ecosystem ใหญ่: npm มี packages มากที่สุดในโลก
  • • Realtime apps: เหมาะกับ WebSocket, chat, gaming

Node.js ใช้ทำอะไรได้บ้าง?

🌐 REST API / GraphQL

Express, Fastify, NestJS

💬 Realtime Apps

Socket.io, WebSocket

🔧 CLI Tools

npm scripts, build tools

🖥️ Desktop Apps

Electron (VS Code, Discord)

Hello World

// hello.js
console.log("Hello, Node.js!");

// รัน
// node hello.js

// HTTP Server
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World!');
});

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

⚙️ ติดตั้ง & npm

ติดตั้ง Node.js

วิธีที่ 1: ดาวน์โหลดจากเว็บ

ไปที่ nodejs.org ดาวน์โหลด LTS version

วิธีที่ 2: ใช้ nvm (แนะนำ)

# ติดตั้ง nvm (Node Version Manager)
# macOS/Linux
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# ติดตั้ง Node.js
nvm install 20
nvm use 20

# ตรวจสอบเวอร์ชัน
node -v   # v20.x.x
npm -v    # 10.x.x

npm - Package Manager

# สร้างโปรเจกต์ใหม่
npm init -y

# ติดตั้ง package
npm install express           # dependencies
npm install -D nodemon        # devDependencies

# npm install shortcuts
npm i lodash                  # install
npm i -D jest                 # install --save-dev

# ติดตั้งจาก package.json
npm install

# รัน scripts
npm run dev
npm start
npm test

# ดู packages ที่ติดตั้ง
npm list --depth=0

# อัปเดต packages
npm update
npm outdated                  # ดู packages ที่ล้าสมัย

package.json

{
  "name": "my-app",
  "version": "1.0.0",
  "description": "My Node.js application",
  "main": "src/index.js",
  "scripts": {
    "start": "node src/index.js",
    "dev": "nodemon src/index.js",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^3.0.0",
    "jest": "^29.0.0"
  }
}

📦 Modules

CommonJS (require/exports)

// math.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

// วิธีที่ 1: exports
exports.add = add;
exports.subtract = subtract;

// วิธีที่ 2: module.exports
module.exports = { add, subtract };

// app.js
const math = require('./math');
console.log(math.add(2, 3));      // 5
console.log(math.subtract(5, 2)); // 3

// หรือ destructure
const { add, subtract } = require('./math');
console.log(add(10, 5));          // 15

ES Modules (import/export)

// math.mjs หรือใน package.json ใส่ "type": "module"
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

// default export
export default class Calculator {
  add(a, b) { return a + b; }
}

// app.mjs
import Calculator, { add, subtract } from './math.mjs';

console.log(add(2, 3));
const calc = new Calculator();
console.log(calc.add(10, 5));

Built-in Modules

// ใช้ node: prefix (แนะนำสำหรับ Node 16+)
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const crypto = require('node:crypto');
const os = require('node:os');

// ตัวอย่างการใช้งาน
const filePath = path.join(__dirname, 'data.txt');
console.log(path.basename(filePath));  // data.txt
console.log(path.extname(filePath));   // .txt

console.log(os.platform());  // darwin, linux, win32
console.log(os.cpus().length);  // จำนวน CPU cores

const hash = crypto.createHash('sha256')
                   .update('hello')
                   .digest('hex');

⏳ Async Programming

1. Callbacks (แบบเก่า)

const fs = require('node:fs');

// Callback style
fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error:', err);
    return;
  }
  console.log(data);
});

// Callback hell (ไม่แนะนำ)
fs.readFile('file1.txt', (err, data1) => {
  fs.readFile('file2.txt', (err, data2) => {
    fs.readFile('file3.txt', (err, data3) => {
      // nested callbacks = hard to read
    });
  });
});

2. Promises

const fs = require('node:fs/promises');

// Promise chain
fs.readFile('data.txt', 'utf8')
  .then(data => {
    console.log(data);
    return fs.readFile('data2.txt', 'utf8');
  })
  .then(data2 => console.log(data2))
  .catch(err => console.error(err));

// สร้าง Promise เอง
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

delay(1000).then(() => console.log('Done!'));

// Promise.all - รันพร้อมกัน
Promise.all([
  fs.readFile('file1.txt', 'utf8'),
  fs.readFile('file2.txt', 'utf8'),
  fs.readFile('file3.txt', 'utf8')
]).then(([data1, data2, data3]) => {
  console.log(data1, data2, data3);
});

3. Async/Await (แนะนำ)

const fs = require('node:fs/promises');

async function readFiles() {
  try {
    // อ่านทีละไฟล์ (sequential)
    const data1 = await fs.readFile('file1.txt', 'utf8');
    const data2 = await fs.readFile('file2.txt', 'utf8');
    console.log(data1, data2);
    
    // อ่านพร้อมกัน (parallel)
    const [a, b, c] = await Promise.all([
      fs.readFile('a.txt', 'utf8'),
      fs.readFile('b.txt', 'utf8'),
      fs.readFile('c.txt', 'utf8')
    ]);
    
  } catch (err) {
    console.error('Error:', err);
  }
}

readFiles();

// Top-level await (ES modules)
// const data = await fs.readFile('data.txt', 'utf8');

🏁 สรุป

  • ✅ Node.js รัน JavaScript บนเซิร์ฟเวอร์ด้วย V8 engine
  • ✅ npm คือ package manager - ใช้จัดการ dependencies
  • ✅ CommonJS (require) vs ES Modules (import)
  • ✅ Async programming: Callbacks → Promises → Async/Await
  • ✅ ใช้ async/await กับ try/catch เป็นวิธีที่แนะนำ

📝 แบบฝึกหัด

ระดับง่าย

  1. สร้างโปรเจกต์ด้วย npm init และติดตั้ง express
  2. เขียนโมดูล math.js ที่มี add, subtract, multiply, divide
  3. สร้าง HTTP server ที่ return "Hello World"

ระดับกลาง

  1. อ่านไฟล์ JSON แล้วแสดงข้อมูลด้วย async/await
  2. สร้างฟังก์ชันที่อ่านหลายไฟล์พร้อมกันด้วย Promise.all
  3. เขียนโค้ดที่ handle error ได้อย่างถูกต้อง