Wed. Apr 16th, 2025
Node.js - แนะนำและการเขียนโปรแกรมเบื้องต้นNode.js - แนะนำและการเขียนโปรแกรมเบื้องต้น
Spread the love

Node.js คืออะไร?

Node.js เป็น JavaScript runtime ที่ทำให้เราสามารถรัน JavaScript บนเครื่องเซิร์ฟเวอร์ได้ โดยใช้ V8 JavaScript engine ของ Google Chrome เป็นตัวประมวลผล ทำให้มีประสิทธิภาพสูงและเหมาะสำหรับการพัฒนาแอปพลิเคชันที่ต้องการการตอบสนองแบบ real-time

การติดตั้ง Node.js

  1. ดาวน์โหลด Node.js จาก https://nodejs.org
  2. ติดตั้งตามขั้นตอนปกติ
  3. ตรวจสอบการติดตั้งด้วยคำสั่ง:
node --version
npm --version

การเขียนโปรแกรม Node.js เบื้องต้น

1. Hello World

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

// รันด้วยคำสั่ง: node hello.js

2. การสร้างเว็บเซิร์ฟเวอร์พื้นฐาน

const http = require('http');

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

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

3. การใช้งาน Express Framework

const express = require('express');
const app = express();

// Middleware สำหรับ parsing JSON
app.use(express.json());

// Route พื้นฐาน
app.get('/', (req, res) => {
    res.send('Hello from Express!');
});

// Route รับข้อมูลผู้ใช้
app.get('/users', (req, res) => {
    const users = [
        { id: 1, name: 'John' },
        { id: 2, name: 'Jane' }
    ];
    res.json(users);
});

// เริ่มต้น server
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

4. การจัดการไฟล์ (File System)

const fs = require('fs');

// อ่านไฟล์แบบ Sync
try {
    const data = fs.readFileSync('input.txt', 'utf8');
    console.log(data);
} catch (err) {
    console.error('Error reading file:', err);
}

// อ่านไฟล์แบบ Async
fs.readFile('input.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log(data);
});

// เขียนไฟล์
fs.writeFile('output.txt', 'Hello Node.js!', 'utf8', (err) => {
    if (err) {
        console.error('Error writing file:', err);
        return;
    }
    console.log('File has been written');
});

5. การใช้งาน Promise และ Async/Await

// สร้างฟังก์ชัน Promise
const getData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { id: 1, name: 'John' };
            resolve(data);
            // หรือถ้ามีข้อผิดพลาด: reject(new Error('Something went wrong'));
        }, 1000);
    });
};

// ใช้งาน Promise แบบ .then()
getData()
    .then(data => console.log(data))
    .catch(err => console.error(err));

// ใช้งาน async/await
async function fetchData() {
    try {
        const data = await getData();
        console.log(data);
    } catch (err) {
        console.error(err);
    }
}

6. การสร้าง REST API ด้วย Express

const express = require('express');
const app = express();

app.use(express.json());

let users = [
    { id: 1, name: 'John', email: '[email protected]' },
    { id: 2, name: 'Jane', email: '[email protected]' }
];

// GET all users
app.get('/api/users', (req, res) => {
    res.json(users);
});

// GET user by id
app.get('/api/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ message: 'User not found' });
    res.json(user);
});

// POST new user
app.post('/api/users', (req, res) => {
    const user = {
        id: users.length + 1,
        name: req.body.name,
        email: req.body.email
    };
    users.push(user);
    res.status(201).json(user);
});

// PUT update user
app.put('/api/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ message: 'User not found' });
    
    user.name = req.body.name;
    user.email = req.body.email;
    res.json(user);
});

// DELETE user
app.delete('/api/users/:id', (req, res) => {
    const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
    if (userIndex === -1) return res.status(404).json({ message: 'User not found' });
    
    users.splice(userIndex, 1);
    res.json({ message: 'User deleted' });
});

7. การจัดการกับฐานข้อมูล (MongoDB Example)

const mongoose = require('mongoose');

// เชื่อมต่อ MongoDB
mongoose.connect('mongodb://localhost/mydatabase', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

// สร้าง Schema
const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    createdAt: { type: Date, default: Date.now }
});

// สร้าง Model
const User = mongoose.model('User', userSchema);

// สร้างข้อมูล
async function createUser() {
    try {
        const user = new User({
            name: 'John Doe',
            email: '[email protected]'
        });
        const result = await user.save();
        console.log(result);
    } catch (err) {
        console.error(err);
    }
}

// ค้นหาข้อมูล
async function findUsers() {
    try {
        const users = await User.find();
        console.log(users);
    } catch (err) {
        console.error(err);
    }
}

การจัดการ Package ด้วย npm

การสร้างโปรเจค

npm init

การติดตั้ง Package

# ติดตั้ง package สำหรับโปรเจค
npm install express

# ติดตั้ง package สำหรับ development
npm install nodemon --save-dev

ตัวอย่าง package.json

{
  "name": "my-node-app",
  "version": "1.0.0",
  "description": "My first Node.js application",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.12.3"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

แนวทางการพัฒนาที่ดี

  1. แบ่งโค้ดเป็นโมดูล
// users.js
module.exports = {
    getUsers() {
        // logic here
    },
    createUser(userData) {
        // logic here
    }
};

// app.js
const users = require('./users');

2. ใช้ Environment Variables

// .env
PORT=3000
MONGODB_URI=mongodb://localhost/mydatabase

// app.js
require('dotenv').config();
const port = process.env.PORT || 3000;

3. จัดการ Error อย่างเหมาะสม

process.on('uncaughtException', (err) => {
    console.error('Uncaught Exception:', err);
    process.exit(1);
});

// Middleware จัดการ Error
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

Loading

By tikky

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *