JavaScript
2024-05-15
26 phút đọc
Giới thiệu Node.js: Viết backend bằng JavaScript
Giới thiệu Node.js: Backend với JavaScript
Node.js cho phép bạn dùng JavaScript để viết backend, tận dụng mô hình event-driven, non-blocking I/O.
1. Node.js khác gì trình duyệt?
- Không có DOM, window, document.
- Có module hệ thống:
fs,http,net, ... - Chạy trên V8 nhưng thêm một lớp C++ để xử lý I/O hiệu quả.
2. Tạo HTTP server đơn giản
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js');
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
3. Express – Framework phổ biến
import express from 'express';
const app = express();
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(3000, () => {
console.log('Express server on http://localhost:3000');
});
Node.js là nền tảng tuyệt vời để xây dựng API, real-time application (WebSocket), microservices và nhiều hơn thế nữa – tất cả chỉ với JavaScript.