Node.js & Express.
js Beginner to Advanced Guide
Lesson 1: Introduction to Node.js
What is Node.js?
- Node.js is a JavaScript runtime built on Chrome's V8 engine.
- It allows you to run JavaScript on the server side.
Benefits:
- Fast and lightweight
- Single language (JavaScript) for both client and server
- Asynchronous and non-blocking
Example: Basic Node Server
----------------------------
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("Hello from Node.js server!");
});
server.listen(3000, () => console.log("Server running at http://localhost:3000"));
Lesson 2: Node.js Modules & File System
Modules in Node.js:
- Built-in modules (e.g., fs, http, path)
- Custom/user-defined modules
- Third-party modules (via npm)
Creating a module:
----------------------------
math.js:
function add(a, b) { return a + b; }
module.exports = { add };
app.js:
const math = require('./math');
console.log(math.add(2, 3));
FS Module (File System):
----------------------------
Read File:
fs.readFile("file.txt", "utf-8", (err, data) => { ... });
Write File:
fs.writeFile("file.txt", "Hello", (err) => { ... });
Append File:
Node.js & Express.js Beginner to Advanced Guide
fs.appendFile("file.txt", "More text", (err) => { ... });
Delete File:
fs.unlink("file.txt", (err) => { ... });
Lesson 3: Event Loop, Callbacks, Promises, and Async/Await
JavaScript is single-threaded, but Node.js uses an event loop to handle async operations.
Callback Example:
fs.readFile("file.txt", (err, data) => {
if (err) throw err;
console.log(data);
});
Promise Example:
const readFilePromise = () => {
return new Promise((resolve, reject) => {
fs.readFile("file.txt", (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
};
Async/Await Example:
async function readFile() {
try {
const data = await fs.promises.readFile("file.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
}
Lesson 4: Introduction to Express.js
Express.js simplifies server creation in Node.js.
Install Express:
npm install express
Basic Express Server:
const express = require('express');
const app = express();
Node.js & Express.js Beginner to Advanced Guide
app.use(express.json());
app.get('/', (req, res) => {
res.send("Hello from Express!");
});
app.listen(3000, () => console.log("Listening on port 3000"));
Route Methods:
app.get("/users", ...)
app.post("/users", ...)
app.put("/users/:id", ...)
app.delete("/users/:id", ...)
Lesson 5: Middleware and Routing in Express.js
Middleware functions run before your final route.
Custom Middleware:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
Route Parameters:
app.get("/user/:id", (req, res) => {
res.send("User ID: " + req.params.id);
});
Modular Routes with express.Router:
const router = require('express').Router();
router.get("/", ...);
router.post("/", ...);
module.exports = router;
Lesson 6: Connecting MongoDB with Mongoose
Install Mongoose:
npm install mongoose
Connect to DB:
mongoose.connect("mongodb://localhost:27017/myapp", { useNewUrlParser: true });
Define a Model:
const UserSchema = new mongoose.Schema({
Node.js & Express.js Beginner to Advanced Guide
name: String,
email: String,
});
const User = mongoose.model("User", UserSchema);
CRUD with Mongoose:
await User.create({...});
await User.find();
await User.findByIdAndUpdate(id, {...});
await User.findByIdAndDelete(id);
Lesson 7: Authentication with JWT
Install Packages:
npm install jsonwebtoken bcryptjs dotenv
Register User:
- Hash password with bcrypt
- Create token with jwt.sign()
Login:
- Compare password with bcrypt.compare()
- Return token on success
Auth Middleware:
const auth = (req, res, next) => {
const token = req.header("Authorization");
const decoded = jwt.verify(token, "secret");
req.userId = decoded.id;
next();
};
Lesson 8: Real-Time Communication with Socket.IO
Install:
npm install socket.io
Server (Node.js):
const io = new Server(server);
io.on("connection", socket => {
socket.on("join", userId => socket.join(userId));
socket.on("sendMessage", ({ to, message }) => {
io.to(to).emit("receiveMessage", message);
});
});
Node.js & Express.js Beginner to Advanced Guide
Client (React):
const socket = io("http://localhost:5000");
socket.emit("join", userId);
socket.emit("sendMessage", { to, message });
socket.on("receiveMessage", (msg) => console.log(msg));