Giới thiệu Node.js – JavaScript Runtime cho Backend

1. Node.js là gì?

  • Node.js là một runtime environment (môi trường thực thi) cho JavaScript, được xây dựng trên Engine V8 của Google Chrome.

  • Đặc điểm nổi bật:

    • Chạy JavaScript trên server (thay vì chỉ chạy trên trình duyệt).

    • Non-blocking I/O (xử lý bất đồng bộ, hiệu suất cao).

    • Single-threaded nhưng hỗ trợ đa luồng thông qua Event Loop.

    • Hệ sinh thái phong phú (npm với hơn 1 triệu package).


2. Cài đặt Node.js

Cách cài đặt

  1. Tải từ trang chủhttps://nodejs.org (chọn bản LTS ổn định).

  2. Kiểm tra phiên bản sau khi cài đặt:

    node -v  # Kiểm tra phiên bản Node.js
    npm -v   # Kiểm tra phiên bản npm (Node Package Manager)

Cách chạy một file JavaScript

  • Tạo file app.js:

    console.log("Hello, Node.js!");
  • Chạy file:

    node app.js

3. Cách sử dụng Node.js cơ bản

a. Tạo HTTP Server

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<h1>Hello Node.js!</h1>');
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
  • Mở trình duyệt truy cập http://localhost:3000.

b. Đọc/Ghi file (File System)

const fs = require('fs');

// Đọc file
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Ghi file
fs.writeFile('newfile.txt', 'Hello Node.js!', (err) => {
  if (err) throw err;
  console.log('File saved!');
});

c. Sử dụng npm (Node Package Manager)

  • Khởi tạo dự án:

    npm init -y
  • Cài đặt package (ví dụ: Express.js):

    npm install express
  • Sử dụng Express để tạo web server:

    const express = require('express');
    const app = express();
    
    app.get('/', (req, res) => {
      res.send('Hello from Express!');
    });
    
    app.listen(3000, () => {
      console.log('Express server running on port 3000');
    });

4. Ứng dụng của Node.js

a. Backend Web Development

  • API Servers (RESTful API, GraphQL).

  • Web Frameworks:

    • Express.js (đơn giản, phổ biến).

    • NestJS (kiến trúc rõ ràng, phù hợp cho dự án lớn).

    • Fastify (hiệu năng cao).

b. Real-time Applications

  • Chat apps (Socket.io).

  • Game servers (WebSockets).

  • Live streaming apps.

c. Microservices & Cloud

  • Xây dựng kiến trúc Microservices.

  • Serverless Functions (AWS Lambda, Firebase Functions).

d. DevOps & Scripting

  • Automation scripts (thay thế Bash/Python).

  • Build tools (Webpack, Gulp).

e. Desktop Apps (Electron.js)

  • Visual Studio Code, Slack, Discord đều được xây dựng bằng Electron (Node.js + Chromium).


5. Ưu & Nhược điểm của Node.js

Ưu điểm Nhược điểm
✔ Nhanh, hiệu suất cao nhờ V8 Engine ❌ Không phù hợp cho CPU-intensive tasks (xử lý video, AI)
✔ JavaScript cả Frontend & Backend ❌ Callback hell (nếu không dùng Promise/Async-Await)
✔ Hệ sinh thái npm khổng lồ ❌ Single-threaded (cần Cluster Mode cho đa luồng)
✔ Tốt cho I/O-heavy apps (API, Real-time) ❌ Khó bảo trì nếu code không tổ chức tốt

6. Tài liệu học Node.js


Kết luận

Node.js là công cụ mạnh để xây dựng backend, real-time apps và automation. Nếu bạn đã biết JavaScript, học Node.js sẽ giúp bạn trở thành Full-stack Developer dễ dàng! 🚀

Bạn muốn mình hướng dẫn sâu hơn về phần nào?

  • Cách dùng Express.js?

  • Xây dựng REST API?

  • Kết hợp Node.js với React/Vue?

Chia sẻ

0963286779