Start your journey in server side JavaScript
Start learning step by step
Check your understanding
Prepare for real interviews
Test your skills
Node.js is a JavaScript runtime built on Chrome's V8 engine. It allows you to run JavaScript on the server side.
// Check Node.js version
node -v
Download Node.js from the official website and install it. NPM (Node Package Manager) comes bundled with Node.js.
// Check npm version
npm -v
Create your first Node.js file and run it using the terminal.
// hello.js
console.log("Hello, Node.js!");
// Run in terminal
node hello.js
Node.js modules allow you to split code into reusable files.
// math.js
exports.add = (a, b) => a + b;
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // 8
Node.js has global objects like __dirname, __filename, process, etc.
console.log(__dirname); // Current directory
console.log(__filename); // Current file path
console.log(process.version); // Node.js version
The fs module lets you work with files (create, read, update, delete).
const fs = require('fs');
// Create a file
fs.writeFileSync('test.txt', 'Hello Node.js');
// Read file
const data = fs.readFileSync('test.txt', 'utf-8');
console.log(data);
Node.js supports both synchronous (blocking) and asynchronous (non-blocking) operations.
const fs = require('fs');
// Async (non-blocking)
fs.readFile('test.txt', 'utf-8', (err, data) => {
console.log(data);
});
console.log("This runs first!");
The path module helps you work with file and directory paths.
const path = require('path');
console.log(path.basename(__filename));
console.log(path.extname(__filename));
console.log(path.join(__dirname, 'test.txt'));
The os module provides information about your operating system.
const os = require('os');
console.log(os.platform());
console.log(os.arch());
console.log(os.totalmem());
You can create a basic web server using Node.js built-in http module.
const http = require('http');
const server = http.createServer((req, res) => {
res.write("Hello from Node.js Server!");
res.end();
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Express.js is a lightweight framework for Node.js that makes building web servers and APIs much easier.
// Install Express
npm install express
Create a simple server using Express.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Routing defines how your app responds to different URLs.
app.get('/about', (req, res) => {
res.send('About Page');
});
app.get('/contact', (req, res) => {
res.send('Contact Page');
});
Middleware functions run between request and response. They can modify request/response.
app.use((req, res, next) => {
console.log('Middleware running...');
next();
});
Express can handle JSON data using built-in middleware.
app.use(express.json());
app.post('/data', (req, res) => {
console.log(req.body);
res.send('Data received');
});
Route parameters allow you to pass dynamic values in the URL.
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Query strings send additional data in the URL using ?key=value.
app.get('/search', (req, res) => {
res.send(`Search query: ${req.query.q}`);
});
// Example: /search?q=nodejs
REST APIs use HTTP methods like GET, POST, PUT, DELETE to manage data.
// GET
app.get('/users', (req, res) => res.send('Get users'));
// POST
app.post('/users', (req, res) => res.send('Create user'));
// DELETE
app.delete('/users/:id', (req, res) => res.send('Delete user'));
Serve HTML, CSS, and JS files using Express static middleware.
const express = require('express');
const app = express();
app.use(express.static('public'));
Error handling middleware helps catch and manage errors in your app.
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send('Something went wrong!');
});
Databases store your application data. Common ones with Node.js are MongoDB, MySQL, and PostgreSQL.
// Example (concept)
const users = [
{ id: 1, name: "Ali" },
{ id: 2, name: "Sara" }
];
Mongoose is a library that helps interact with MongoDB easily.
// Install mongoose
npm install mongoose
Connect your Node.js app to MongoDB using Mongoose.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testDB')
.then(() => console.log('Connected to DB'))
.catch(err => console.log(err));
A schema defines the structure of your data. A model allows interaction with the database.
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model('User', userSchema);
You can save data into MongoDB using your model.
const user = new User({
name: "Zohil",
age: 20
});
user.save()
.then(() => console.log('User saved'))
.catch(err => console.log(err));
Retrieve data from MongoDB using your model.
app.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
Add new data into the database using POST requests.
app.post('/users', async (req, res) => {
const newUser = new User(req.body);
await newUser.save();
res.json(newUser);
});
Update existing records using PUT requests.
app.put('/users/:id', async (req, res) => {
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
res.json(updatedUser);
});
Remove data from the database using DELETE requests.
app.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.send('User deleted');
});
Authentication verifies users. A simple example is checking username and password.
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === '1234') {
res.send('Login successful');
} else {
res.status(401).send('Invalid credentials');
}
});
Never store plain passwords. Use bcrypt to hash passwords securely.
// Install bcrypt
npm install bcrypt
const bcrypt = require('bcrypt');
const hashed = await bcrypt.hash('1234', 10);
console.log(hashed);
Use bcrypt to compare entered password with hashed password.
const match = await bcrypt.compare('1234', hashedPassword);
if (match) {
console.log('Password correct');
} else {
console.log('Wrong password');
}
JWT (JSON Web Token) is used for secure user authentication.
// Install JWT
npm install jsonwebtoken
const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: 1 }, 'secretKey');
console.log(token);
Use middleware to protect routes and allow only authenticated users.
const jwt = require('jsonwebtoken');
function auth(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).send('Access denied');
try {
const verified = jwt.verify(token, 'secretKey');
req.user = verified;
next();
} catch {
res.status(400).send('Invalid token');
}
}
Use environment variables to store sensitive data like API keys and secrets.
// Install dotenv
npm install dotenv
require('dotenv').config();
console.log(process.env.SECRET_KEY);
Deployment means putting your app online so others can access it. Popular platforms: Vercel, Render, Railway.
# Start your app
node app.js
# Or use package.json
npm start
Nodemon automatically restarts your server when files change (great for development).
# Install nodemon
npm install -g nodemon
# Run app
nodemon app.js
MVC (Model-View-Controller) helps organize your code into clean, scalable structure.
/models
/controllers
/routes
/app.js
Optimize your Node.js app for speed and scalability.
// Use caching
// Use async code
// Avoid blocking operations
// Use clustering (advanced)
Build a full project to master everything:
Project: User Management System
Features:
- Register/Login (JWT)
- CRUD Users
- MongoDB Database
- Protected Routes
- Deployment
Tech Stack:
Node.js + Express + MongoDB
1. What is Node.js primarily used for?
2. Node.js is built on which JavaScript engine?
3. Which module is used to create a basic HTTP server in Node.js?
4. Which function reads a file asynchronously in Node.js?
5. Which Node.js module is used to work with the file system?
6. What is npm in Node.js?
7. Which Node.js feature allows handling multiple operations without blocking?
8. How do you include a module in Node.js?
9. Which method is used to send a response in an HTTP server?
10. Which global object in Node.js provides information about the environment?
11. Which method converts a JavaScript object to a JSON string?
12. Which Node.js module is used to work with URLs?
13. Which method is used to listen to a port in Node.js HTTP server?
14. Which of the following is NOT a built-in Node.js module?