Home
Education
D/L Mode
HTML CSS JavaScript Python SQL Node.js PHP Java C++

Welcome to Node.js

Start your journey in server side JavaScript

Lessons

Start learning step by step

Question & Answer

Check your understanding

Interview Asked Questions

Prepare for real interviews

Quiz

Test your skills

🟒 Node.js Lesson 1: Introduction to Node.js

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
    
βœ”

🟒 Node.js Lesson 2: Installing Node.js

Download Node.js from the official website and install it. NPM (Node Package Manager) comes bundled with Node.js.

// Check npm version
npm -v
    
βœ”

🟒 Node.js Lesson 3: First Node.js Script

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 Lesson 4: Modules

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 Lesson 5: Global Objects

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
    
βœ”

🟒 Node.js Lesson 6: File System (fs)

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 Lesson 7: Asynchronous vs Synchronous

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!");
    
βœ”

🟒 Node.js Lesson 8: Path Module

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'));
    
βœ”

🟒 Node.js Lesson 9: OS Module

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());
    
βœ”

🟒 Node.js Lesson 10: Creating a Server

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");
});
    
βœ”

🟒 Node.js Lesson 11: What is Express.js?

Express.js is a lightweight framework for Node.js that makes building web servers and APIs much easier.

// Install Express
npm install express
    
βœ”

🟒 Node.js Lesson 12: Creating an Express Server

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');
});
    
βœ”

🟒 Node.js Lesson 13: Routing

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');
});
    
βœ”

🟒 Node.js Lesson 14: Middleware

Middleware functions run between request and response. They can modify request/response.

app.use((req, res, next) => {
  console.log('Middleware running...');
  next();
});
    
βœ”

🟒 Node.js Lesson 15: Handling JSON Data

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');
});
    
βœ”

🟒 Node.js Lesson 16: Route Parameters

Route parameters allow you to pass dynamic values in the URL.

app.get('/user/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});
    
βœ”

🟒 Node.js Lesson 17: Query Strings

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
    
βœ”

🟒 Node.js Lesson 18: REST API Basics

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'));
    
βœ”

🟒 Node.js Lesson 19: Serving Static Files

Serve HTML, CSS, and JS files using Express static middleware.

const express = require('express');
const app = express();

app.use(express.static('public'));
    
βœ”

🟒 Node.js Lesson 20: Handling Errors

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!');
});
    
βœ”

🟒 Node.js Lesson 21: Introduction to Databases

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" }
];
    
βœ”

🟒 Node.js Lesson 22: Installing MongoDB & Mongoose

Mongoose is a library that helps interact with MongoDB easily.

// Install mongoose
npm install mongoose
    
βœ”

🟒 Node.js Lesson 23: Connecting to MongoDB

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));
    
βœ”

🟒 Node.js Lesson 24: Creating a Schema & Model

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);
    
βœ”

🟒 Node.js Lesson 25: Saving Data to Database

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));
    
βœ”

🟒 Node.js Lesson 26: Fetching Data (GET)

Retrieve data from MongoDB using your model.

app.get('/users', async (req, res) => {
  const users = await User.find();
  res.json(users);
});
    
βœ”

🟒 Node.js Lesson 27: Creating Data (POST)

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);
});
    
βœ”

🟒 Node.js Lesson 28: Updating Data (PUT)

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);
});
    
βœ”

🟒 Node.js Lesson 29: Deleting Data (DELETE)

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');
});
    
βœ”

🟒 Node.js Lesson 30: Basic Authentication Concept

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');
  }
});
    
βœ”

🟒 Node.js Lesson 31: Password Hashing (bcrypt)

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);
    
βœ”

🟒 Node.js Lesson 32: Comparing Passwords

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');
}
    
βœ”

🟒 Node.js Lesson 33: JWT Authentication

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);
    
βœ”

🟒 Node.js Lesson 34: Protecting Routes

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');
  }
}
    
βœ”

🟒 Node.js Lesson 35: Environment Variables

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);
    
βœ”

🟒 Node.js Lesson 36: Deployment Basics

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
    
βœ”

🟒 Node.js Lesson 37: Using Nodemon

Nodemon automatically restarts your server when files change (great for development).

# Install nodemon
npm install -g nodemon

# Run app
nodemon app.js
    
βœ”

🟒 Node.js Lesson 38: MVC Structure

MVC (Model-View-Controller) helps organize your code into clean, scalable structure.

/models
/controllers
/routes
/app.js
    
βœ”

🟒 Node.js Lesson 39: Performance Tips

Optimize your Node.js app for speed and scalability.

// Use caching
// Use async code
// Avoid blocking operations
// Use clustering (advanced)
    
βœ”

🟒 Node.js Lesson 40: Final Project Idea

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
    
πŸŽ‰ Congratulations! You have completed all Node.JS lessons!
Keep practicing and building amazing Applications!
βœ”

πŸ’‘Node.js Questions & Answers

❓ What is Node.js?
Node.js is a JavaScript runtime built on Chrome's V8 engine that allows executing JavaScript on the server side to build scalable and fast network applications.
❓ What are the key features of Node.js?
Node.js features include non-blocking I/O, event-driven architecture, single-threaded but scalable design, fast performance due to V8 engine, and a vast NPM ecosystem.
❓ What is the Event Loop in Node.js?
The Event Loop allows Node.js to perform non-blocking I/O by offloading operations to the system kernel and executing callbacks asynchronously.
❓ What is NPM in Node.js?
NPM (Node Package Manager) is the default package manager for Node.js. It allows developers to install, share, and manage dependencies and packages.
❓ What is the difference between Node.js and JavaScript in the browser?
JavaScript in the browser is client-side and manipulates the DOM, while Node.js runs JavaScript on the server to handle files, databases, and network requests.
❓ What is the difference between synchronous and asynchronous code in Node.js?
Synchronous code runs line by line and blocks execution until the current operation finishes. Asynchronous code allows other operations to run while waiting for tasks like file I/O or network requests to complete.
❓ What are Node.js streams?
Streams are objects that let you read or write data piece by piece, rather than all at once. They are useful for handling large files or data efficiently.
❓ What is a callback in Node.js?
A callback is a function passed as an argument to another function, executed after a task completes. Node.js heavily uses callbacks for asynchronous operations.
❓ What is the difference between `require()` and `import` in Node.js?
`require()` is used in CommonJS modules (default in Node.js) to load modules, while `import` is used in ES6 modules. ES6 modules support static analysis and modern syntax.
❓ What is the difference between `process.nextTick()` and `setImmediate()`?
`process.nextTick()` executes a callback immediately after the current operation completes, before the event loop continues. `setImmediate()` executes a callback on the next iteration of the event loop.
❓ What is the difference between `fs.readFile()` and `fs.createReadStream()`?
`fs.readFile()` reads the entire file into memory at once (synchronous or asynchronous), while `fs.createReadStream()` reads the file in chunks, which is more memory-efficient for large files.
❓ What is middleware in Node.js?
Middleware is a function that has access to the request and response objects in an application. It can modify requests, responses, or end the request-response cycle, commonly used in frameworks like Express.js.
❓ What is the difference between `app.use()` and `app.get()` in Express.js?
`app.use()` mounts middleware for all HTTP methods and paths, while `app.get()` handles GET requests for a specific route.
❓ What is the difference between CommonJS and ES6 modules in Node.js?
CommonJS uses `require()` and `module.exports`. ES6 modules use `import` and `export`. ES6 modules are statically analyzed, support tree-shaking, and are standard in modern JavaScript.
❓ What is the purpose of `package.json` in Node.js?
`package.json` stores metadata about a Node.js project, including dependencies, scripts, version, entry point, and configuration for tools like NPM.
❓ What is the difference between `process.env` and configuration files?
`process.env` holds environment variables available at runtime. Configuration files store project-specific settings. Using `process.env` is preferred for sensitive data like API keys.
❓ What is the difference between `setTimeout()` and `setInterval()` in Node.js?
`setTimeout()` executes a function once after a specified delay, while `setInterval()` repeatedly executes a function at a specified interval.
❓ What is the difference between `process.nextTick()` and Promises?
`process.nextTick()` queues a callback to execute after the current operation before the event loop continues. Promises schedule tasks in the microtask queue, which runs after the current call stack but after `process.nextTick()`.
❓ What is a cluster in Node.js?
A cluster is a way to create multiple Node.js processes to take advantage of multi-core CPUs, improving performance and reliability by distributing load across workers.
❓ What is the difference between `require()` cache and reloading modules?
Node.js caches modules loaded with `require()` to improve performance. Reloading requires deleting the module from `require.cache` before requiring it again.
❓ What is the difference between blocking and non-blocking I/O in Node.js?
Blocking I/O operations halt execution until the task completes. Non-blocking I/O allows Node.js to continue executing other tasks while waiting for the operation to finish.
❓ What is the difference between synchronous and asynchronous file operations in Node.js?
Synchronous file operations block execution until the task completes. Asynchronous file operations use callbacks or Promises and allow other code to execute while waiting for completion.
❓ What are buffers in Node.js?
Buffers are temporary memory allocations used to store raw binary data. They are commonly used when reading from or writing to streams, files, or network sockets.
❓ What is the difference between `readFile` and `createReadStream` in Node.js?
`readFile` reads the entire file into memory at once, which can be heavy for large files. `createReadStream` reads the file in chunks, allowing memory-efficient processing of large files.
❓ What is Express.js?
Express.js is a minimal and flexible Node.js framework that provides a robust set of features for building web and API applications, including routing, middleware support, and template rendering.
❓ What is CORS and how is it handled in Node.js?
CORS (Cross-Origin Resource Sharing) is a security feature that restricts requests from different origins. In Node.js, it can be handled using the `cors` middleware in Express.js to allow or restrict access.
❓ What is the difference between `app.use()` and `app.all()` in Express.js?
`app.use()` mounts middleware for all HTTP methods on a path. `app.all()` is used to match all HTTP methods for a specific route, often for route-specific logic.
❓ What is a Promise in Node.js?
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It allows chaining `.then()` and `.catch()` for better asynchronous control.
❓ What is the difference between `process.nextTick()`, `setImmediate()`, and `setTimeout()`?
`process.nextTick()` executes callbacks after the current operation, before the event loop continues. `setImmediate()` executes callbacks in the next iteration of the event loop. `setTimeout()` executes after a specified delay.
❓ How do you handle errors in Node.js?
Errors in Node.js can be handled using callbacks (`err` argument), Promises with `.catch()`, `async/await` with `try/catch`, or error-handling middleware in Express.js for web applications.

🎯 Node.js Interview Questions

❓ What is Node.js?
Node.js is a JavaScript runtime built on Chrome's V8 engine that allows executing JavaScript on the server side to build scalable and fast network applications.
❓ What are the key features of Node.js?
Node.js features include non-blocking I/O, event-driven architecture, single-threaded but scalable design, fast performance due to V8 engine, and a large NPM ecosystem.
❓ What is the Event Loop in Node.js?
The Event Loop allows Node.js to perform non-blocking I/O operations by handling asynchronous callbacks efficiently, ensuring scalability.
❓ What is NPM?
NPM (Node Package Manager) is the default package manager for Node.js. It manages dependencies, packages, and scripts for Node.js projects.
❓ What is the difference between synchronous and asynchronous code in Node.js?
Synchronous code blocks execution until completion, while asynchronous code allows other tasks to execute while waiting for an operation to finish, using callbacks, Promises, or async/await.
❓ What is middleware in Node.js?
Middleware is a function that has access to the request and response objects, allowing modification or termination of the request-response cycle, commonly used in Express.js.
❓ What is the difference between `require()` and `import`?
`require()` is used in CommonJS modules (Node.js default), while `import` is used in ES6 modules. ES6 modules support static analysis and modern syntax like tree-shaking.
❓ What is the difference between `process.nextTick()` and `setImmediate()`?
`process.nextTick()` executes a callback after the current operation, before continuing the event loop. `setImmediate()` executes a callback on the next iteration of the event loop.
❓ What is Express.js?
Express.js is a minimal and flexible Node.js web framework that provides routing, middleware support, and utilities for building web applications and APIs.
❓ How do you handle errors in Node.js?
Errors in Node.js are handled using callbacks with an error argument, Promises with `.catch()`, `async/await` with `try/catch`, or error-handling middleware in frameworks like Express.js.

πŸ“ Node.js Quiz: Test Your Knowledge

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?

×