Full-stack Developer chuyên về Java Backend và JavaScript Frontend. Sẵn sàng đóng góp vào các dự án web development với kỹ năng vững chắc và tinh thần học hỏi không ngừng.
Mục lục
Mục lục
🚀 Discover Node.js - bring JavaScript to the server! Build REST APIs, real-time apps, microservices và hơn thế nữa với JavaScript!
graph TB
A[Node.js] --> B[V8 Engine]
A --> C[Event Loop]
A --> D[NPM Ecosystem]
A --> E[Non-blocking I/O]
B --> F[Fast Execution]
C --> G[Async Operations]
D --> H[Millions of Packages]
E --> I[High Scalability]
style A fill:#68a063
style B fill:#339af0
style C fill:#ff6b6b
style D fill:#ffd43b
5 đặc điểm nổi bật:
Asynchronous
Non-blocking I/O - handle thousands of connections!
Single-threaded
But highly scalable with Event Loop
V8 Engine
Lightning fast - compile JS to machine code
// File: math.mjs - hoặc dùng "type": "module" trong package.json
exportconstadd=(a,b)=>a+b;exportconstsubtract=(a,b)=>a-b;exportdefault{multiply:(a,b)=>a*b,divide:(a,b)=>a/b};
consthttp=require('http');// Create server
constserver=http.createServer((req,res)=>{// Set response header
res.writeHead(200,{'Content-Type':'text/html'});// Send response
res.write('<h1>Hello from Node.js Server!</h1>');res.write('<p>Welcome to my first server</p>');res.end();});// Start server
constPORT=3000;server.listen(PORT,()=>{console.log(`🚀 Server running on http://localhost:${PORT}`);});
consthttp=require('http');constserver=http.createServer((req,res)=>{consturl=req.url;constmethod=req.method;// Home page
if(url==='/'||url==='/home'){res.writeHead(200,{'Content-Type':'text/html'});res.write('<h1>Home Page</h1>');res.write('<a href="/about">About</a>');res.end();}// About page
elseif(url==='/about'){res.writeHead(200,{'Content-Type':'text/html'});res.write('<h1>About Page</h1>');res.write('<p>This is the about page</p>');res.end();}// API endpoint
elseif(url==='/api/users'){res.writeHead(200,{'Content-Type':'application/json'});constusers=[{id:1,name:'Trung Tín'},{id:2,name:'Nguyễn Văn A'}];res.end(JSON.stringify(users));}// 404 Not Found
else{res.writeHead(404,{'Content-Type':'text/html'});res.write('<h1>404 - Page Not Found</h1>');res.end();}});server.listen(3000,()=>{console.log('Server running on port 3000');});
# Cài đặt package (dependencies)npm install express
npm i express
# Cài đặt dev dependenciesnpm install --save-dev nodemon
npm i -D nodemon
# Cài đặt globalnpm install -g nodemon
# Cài đặt specific versionnpm install express@4.17.1
{"name":"my-node-app","version":"1.0.0","description":"My first Node.js app","main":"app.js","scripts":{"start":"node app.js","dev":"nodemon app.js","test":"echo \"Error: no test specified\" && exit 1"},"keywords":["nodejs","javascript"],"author":"Trung Tín","license":"ISC","dependencies":{"express":"^4.18.2"},"devDependencies":{"nodemon":"^2.0.22"}}
constexpress=require('express');constapp=express();// Middleware để parse JSON
app.use(express.json());// Routes
app.get('/',(req,res)=>{res.send('<h1>Welcome to Express!</h1>');});app.get('/api/users',(req,res)=>{constusers=[{id:1,name:'Trung Tín',age:20},{id:2,name:'Nguyễn Văn A',age:22}];res.json(users);});app.get('/api/users/:id',(req,res)=>{constid=parseInt(req.params.id);constuser={id,name:'User '+id};res.json(user);});app.post('/api/users',(req,res)=>{constnewUser=req.body;console.log('New user:',newUser);res.status(201).json({message:'User created',user:newUser});});// Start server
constPORT=process.env.PORT||3000;app.listen(PORT,()=>{console.log(`🚀 Server running on port ${PORT}`);});
constexpress=require('express');constapp=express();app.use(express.json());// In-memory database
letbooks=[{id:1,title:'JavaScript: The Good Parts',author:'Douglas Crockford'},{id:2,title:'Eloquent JavaScript',author:'Marijn Haverbeke'}];// GET - Lấy tất cả books
app.get('/api/books',(req,res)=>{res.json(books);});// GET - Lấy book theo ID
app.get('/api/books/:id',(req,res)=>{constbook=books.find(b=>b.id===parseInt(req.params.id));if(!book){returnres.status(404).json({error:'Book not found'});}res.json(book);});// POST - Tạo book mới
app.post('/api/books',(req,res)=>{const{title,author}=req.body;// Validation
if(!title||!author){returnres.status(400).json({error:'Title and author required'});}constnewBook={id:books.length+1,title,author};books.push(newBook);res.status(201).json(newBook);});// PUT - Update book
app.put('/api/books/:id',(req,res)=>{constbook=books.find(b=>b.id===parseInt(req.params.id));if(!book){returnres.status(404).json({error:'Book not found'});}const{title,author}=req.body;if(title)book.title=title;if(author)book.author=author;res.json(book);});// DELETE - Xóa book
app.delete('/api/books/:id',(req,res)=>{constindex=books.findIndex(b=>b.id===parseInt(req.params.id));if(index===-1){returnres.status(404).json({error:'Book not found'});}books.splice(index,1);res.status(204).send();});app.listen(3000,()=>{console.log('Books API running on port 3000');});
# GET all bookscurl http://localhost:3000/api/books
# GET book by IDcurl http://localhost:3000/api/books/1
# POST new bookcurl -X POST http://localhost:3000/api/books \
-H "Content-Type: application/json"\
-d '{"title":"Node.js Design Patterns","author":"Mario Casciaro"}'# PUT update bookcurl -X PUT http://localhost:3000/api/books/1 \
-H "Content-Type: application/json"\
-d '{"title":"Updated Title"}'# DELETE bookcurl -X DELETE http://localhost:3000/api/books/1
constexpress=require('express');constapp=express();// Logger middleware
app.use((req,res,next)=>{console.log(`${req.method}${req.url} - ${newDate().toISOString()}`);next();// Chuyển sang middleware tiếp theo
});// Authentication middleware
constauthenticate=(req,res,next)=>{consttoken=req.headers['authorization'];if(!token){returnres.status(401).json({error:'No token provided'});}// Verify token (simplified)
if(token==='secret-token'){next();}else{res.status(403).json({error:'Invalid token'});}};// Public route
app.get('/api/public',(req,res)=>{res.json({message:'This is public'});});// Protected route
app.get('/api/protected',authenticate,(req,res)=>{res.json({message:'This is protected'});});app.listen(3000);