I. What Exactly is Node.js?¶
In simple terms, Node.js is a tool that allows JavaScript to run on the server side. It is built on Chrome’s V8 engine, enabling developers to write backend code using JavaScript syntax to handle tasks like file operations, database interactions, and network requests.
Why learn Node.js? Its core advantages are non-blocking I/O (can be understood as “doing one thing while waiting, without getting stuck”) and event-driven (like a waiter taking orders—they don’t need to watch you constantly; they only act when an order is received). These features make it particularly suitable for handling high-concurrency asynchronous tasks (e.g., processing 100 user requests simultaneously).
II. What Can Node.js Do?¶
- Web Application Development: Use frameworks like Express or Koa to quickly build websites (e.g., parts of Zhihu and Alibaba’s business systems).
- API Interface Development: Write backend interfaces for frontend calls (e.g., backends for WeChat mini-programs or mobile apps).
- Real-time Applications: Implement instant messaging with Socket.io (e.g., online chat, live弹幕).
- Command-line Tools: Use Node to write scripts for automation (e.g., auto-generating code, batch file processing).
- Data Analysis/Crawling: Process log files and scrape web data (e.g., website traffic statistics).
III. 5 Must-Do Practical Projects for Beginners¶
Project 1: Personal Blog Website (Beginner-friendly: Express + Template Engine)¶
Goal: Build a static blog that displays article lists and single articles, using local files to store articles.
Technologies: Express (web framework), EJS (template engine), fs module (file reading/writing).
Steps:
1. Install Express: npm init -y && npm install express ejs
2. Create the project structure:
blog/
├─ views/
│ ├─ index.ejs # Article list page
│ └─ post.ejs # Single article page
├─ app.js # Entry file
└─ posts/ # Folder to store articles (each article is a .md or .txt file)
- Write the entry file
app.js:
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
app.set('view engine', 'ejs'); // Use EJS template engine
// Home page: Read articles from the posts folder and render the list
app.get('/', (req, res) => {
fs.readdirSync(path.join(__dirname, 'posts')).forEach(file => {
const content = fs.readFileSync(path.join(__dirname, 'posts', file), 'utf8');
res.render('index', { posts: [{ title: file, content }] }); // Simplified example
});
});
app.listen(3000, () => console.log('Blog running at http://localhost:3000'));
- Write article list rendering code in
views/index.ejs(simple loop).
Why Beginner-friendly: No database required—pure file operations. Familiarizes you with routing and template rendering, providing a strong sense of accomplishment.
Project 2: Command-line To-Do List Tool (Beginner-friendly: Command-line Interaction + File Operations)¶
Goal: Add, view, and delete to-do items via the command line, storing data in a local file.
Technologies: commander (parse command-line arguments), fs module (JSON file storage).
Steps:
1. Install dependencies: npm init -y && npm install commander
2. Write todo.js:
const { program } = require('commander');
const fs = require('fs');
const path = require('path');
const TODO_FILE = path.join(__dirname, 'todos.json');
// Initialize to-do array
let todos = [];
if (fs.existsSync(TODO_FILE)) {
todos = JSON.parse(fs.readFileSync(TODO_FILE, 'utf8'));
}
// Add a to-do item (command: node todo.js add "Learn Node.js")
program.command('add <content>').action(content => {
todos.push({ id: Date.now(), content, completed: false });
fs.writeFileSync(TODO_FILE, JSON.stringify(todos));
console.log('Added successfully!');
});
// List to-do items (command: node todo.js list)
program.command('list').action(() => {
console.log(todos.map(t => `[${t.completed ? '✓' : '□'}] ${t.content}`).join('\n'));
});
program.parse(process.argv);
- Test commands:
node todo.js add "Write a blog",node todo.js list.
Why Beginner-friendly: Zero frontend knowledge required. Pure command-line operations help understand asynchronous file I/O and JSON processing.
Project 3: Simple RESTful API (Beginner-friendly: Express + Data Storage)¶
Goal: Build a user management API to support adding, querying, and deleting user information.
Technologies: Express (routing), fs module (JSON file storage), Postman (testing).
Steps:
1. Install Express: npm init -y && npm install express
2. Write api.js:
const express = require('express');
const app = express();
app.use(express.json()); // Parse JSON request bodies
const fs = require('fs');
const path = require('path');
const USER_FILE = path.join(__dirname, 'users.json');
// Initialize user data (if file doesn't exist)
if (!fs.existsSync(USER_FILE)) {
fs.writeFileSync(USER_FILE, JSON.stringify([]));
}
// 1. Get all users
app.get('/users', (req, res) => {
const users = JSON.parse(fs.readFileSync(USER_FILE, 'utf8'));
res.json(users);
});
// 2. Add a user
app.post('/users', (req, res) => {
const newUser = { id: Date.now(), ...req.body };
const users = JSON.parse(fs.readFileSync(USER_FILE, 'utf8'));
users.push(newUser);
fs.writeFileSync(USER_FILE, JSON.stringify(users));
res.json(newUser);
});
app.listen(3000, () => console.log('API running at http://localhost:3000'));
- Test with Postman: Send a
POST /usersrequest with{name: "Xiaoming"}in the body, then check the user list.
Why Beginner-friendly: Learn HTTP methods (GET/POST), routing design, and backend data logic.
Project 4: Real-time Chat Application (Beginner-friendly: Socket.io + Real-time Communication)¶
Goal: Enable two browser windows to send messages to each other for simple chat functionality.
Technologies: Express (server), Socket.io (WebSocket for real-time communication).
Steps:
1. Install dependencies: npm init -y && npm install express socket.io
2. Write server.js:
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve static files (client pages)
app.use(express.static('public'));
// Listen for connections
io.on('connection', (socket) => {
console.log('New user connected');
// Receive messages
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Broadcast to all users
});
socket.on('disconnect', () => console.log('User disconnected'));
});
server.listen(3000, () => console.log('Chat server running at http://localhost:3000'));
- Write the chat interface in
public/index.html:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const input = document.getElementById('msg');
const button = document.getElementById('send');
button.onclick = () => {
socket.emit('chat message', input.value);
input.value = '';
};
socket.on('chat message', (msg) => {
const div = document.createElement('div');
div.textContent = msg;
document.body.appendChild(div);
});
</script>
- Open two browser windows at
http://localhost:3000and test message sending.
Why Beginner-friendly: First exposure to “real-time communication”—understand WebSocket principles without complex HTTP requests.
Project 5: Weather Query Tool (Beginner-friendly: Third-party API Integration)¶
Goal: Input a city name via the command line to return weather information (using a public API).
Technologies: axios (HTTP requests), process.argv (parse command-line arguments).
Steps:
1. Install axios: npm init -y && npm install axios
2. Write weather.js:
const axios = require('axios');
const apiKey = 'Your weather API key'; // Apply for a free key from He Weather/Amap Weather API
// Get command-line argument (e.g., node weather.js Beijing)
const city = process.argv[2];
if (!city) {
console.log('Please enter a city name: node weather.js Beijing');
process.exit();
}
// Call weather API (example using He Weather API)
axios.get(`https://devapi.qweather.com/v7/weather/now?location=${city}&key=${apiKey}`)
.then(res => {
const data = res.data;
if (data.code === '200') {
console.log(`Weather: ${data.now.text}`);
console.log(`Temperature: ${data.now.temp}°C`);
} else {
console.log('Query failed. Check city name or API key.');
}
})
.catch(err => console.log('Request error:', err));
- Replace
apiKey, then runnode weather.js Beijing.
Why Beginner-friendly: Learn external API integration, handle asynchronous requests, and improve data acquisition skills.
IV. Conclusion¶
Node.js is not difficult to get started with, but the key is hands-on practice! Start with simple command-line tools and gradually transition to web applications. Each project helps you master core concepts like routing, file operations, and asynchronous requests. When facing problems, consult documentation and examples. By completing these 5 projects, you’ll be proficient in using Node.js to solve real-world problems.
Now, pick one project and start coding! 👇