Node.js เป็นแพลตฟอร์มสำหรับพัฒนา Web Application และ API ที่ทำงานบน JavaScript ฝั่ง Server
ซึ่งนิยมใช้งานร่วมกับ Framework อย่าง Express.js และฐานข้อมูล เช่น
PostgreSQL, MySQL หรือ MongoDB เพื่อสร้างระบบ Backend ที่มีประสิทธิภาพ
1. ติดตั้ง Node.js
เริ่มต้นด้วยการติดตั้ง Node.js โดยสามารถดาวน์โหลดได้จากเว็บไซต์ทางการ
- เข้าเว็บไซต์ https://nodejs.org
- ดาวน์โหลดเวอร์ชัน LTS (Long Term Support)
- ทำการติดตั้งตามขั้นตอน
เมื่อติดตั้งเสร็จแล้ว สามารถตรวจสอบเวอร์ชันได้ด้วยคำสั่ง
node -v
npm -v
หากแสดงหมายเลขเวอร์ชัน แสดงว่าการติดตั้งสำเร็จแล้ว
2. สร้างโปรเจกต์ Node.js
สร้างโฟลเดอร์สำหรับโปรเจกต์ และเริ่มต้น Node.js project
mkdir my-node-app
cd my-node-app
npm init -y
คำสั่ง npm init -y จะสร้างไฟล์ package.json
ซึ่งใช้สำหรับจัดการ dependency ของโปรเจกต์
3. ติดตั้ง Express Framework
Express เป็น Framework ที่ช่วยให้การสร้าง Web Server และ REST API ทำได้ง่ายขึ้น
npm install express
หลังจากติดตั้งแล้ว จะมีโฟลเดอร์ node_modules และ dependency ถูกบันทึกใน package.json
4. สร้าง Server ด้วย Express
สร้างไฟล์ชื่อ server.js
const express = require('express');
const app = express();app.get('/', (req, res) => {
res.send('Hello Node.js + Express');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
จากนั้นรัน Server ด้วยคำสั่ง
node server.js
เปิด Browser ไปที่
http://localhost:3000
จะเห็นข้อความ Hello Node.js + Express
5. ติดตั้งฐานข้อมูล (PostgreSQL หรือ MySQL)
Node.js สามารถเชื่อมต่อฐานข้อมูลได้หลายประเภท ตัวอย่างการติดตั้ง PostgreSQL
npm install pg
ตัวอย่างโค้ดเชื่อมต่อ PostgreSQL
const { Pool } = require('pg');const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'testdb',
password: '1234',
port: 5432,
});
pool.query('SELECT NOW()', (err, res) => {
console.log(res.rows);
});
6. โครงสร้างโปรเจกต์ที่นิยมใช้
เมื่อโปรเจกต์เริ่มใหญ่ขึ้น มักจะจัดโครงสร้างโฟลเดอร์ดังนี้
my-node-app
│
├── server.js
├── package.json
│
├── routes
│ └── users.js
│
├── controllers
│ └── userController.js
│
├── models
│ └── db.js
│
└── node_modules
ตัวอย่างการใช้งานจริง
Node.js + Express มักถูกใช้ในระบบต่าง ๆ เช่น
- REST API สำหรับ Mobile Application
- Backend สำหรับ Web Application
- ระบบ Microservices
- ระบบ Real-time เช่น Chat หรือ Notification
สรุป
การพัฒนา Backend ด้วย Node.js เริ่มต้นจากการติดตั้ง Node.js
จากนั้นสร้างโปรเจกต์ด้วย npm และติดตั้ง Framework อย่างExpress.js เพื่อสร้าง Web Server
และสามารถเชื่อมต่อฐานข้อมูล เช่น PostgreSQL หรือ MySQL
เพื่อพัฒนาระบบ API หรือ Web Application ได้อย่างมีประสิทธิภาพ
