NodeJS & ExpressJS
Introduction
Node.js is a powerful, event-driven, non-blocking JavaScript runtime that allows developers to build scalable and high-performance backend applications. It is built on Google Chrome's V8 JavaScript engine, making it fast and efficient for server-side development.
Express.js is a lightweight and flexible web framework for Node.js, designed to simplify the process of building web applications and APIs. It provides essential features like routing, middleware, and HTTP handling, making backend development smoother.
Why Use Node.js?
Asynchronous & Non-blocking – Handles multiple requests efficiently.
High Performance – Uses V8 Engine, which compiles JavaScript to machine code.
Single Programming Language – JavaScript can be used for both frontend & backend.
Huge Ecosystem – Over 1.5 million packages available via npm.
Microservices & Real-time Apps – Ideal for APIs, chat apps, and live streaming.
Scalability – Perfect for handling thousands of concurrent users.
Why Use Express.js?
Minimal & Fast – No unnecessary bloat; just the essentials.
Easy Routing System – Handles URLs efficiently.
Middleware Support – Customize requests and responses.
Template Engines – Supports EJS, Pug, and Handlebars for dynamic HTML.
API Development – Ideal for creating RESTful & GraphQL APIs.
Getting Started with Node.js & Express.js
1️⃣ Install Node.js
Download and install Node.js from https://nodejs.org. Check the installation:
2️⃣ Initialize a New Project
Create a new project and set up package.json
:
3️⃣ Install Express.js
Creating a Simple Express Server
Create a server.js
file and add the following:
Run the server:
Now, open http://localhost:3000/ in your browser.
Express.js Routing
Defining Different Routes
Handling URL Parameters
Visit: http://localhost:3000/user/John
Output: "Hello, John!"
Using Middleware in Express.js
Middleware functions allow you to modify requests/responses before they reach the final handler.
Example of Middleware
Built-in Middleware
Third-party Middleware (CORS, Morgan)
Serving Static Files (HTML, CSS, Images, JS)
Express can serve static files from a directory like public/
.
Place HTML, CSS, JS, images inside the public/
folder, and access them directly in the browser.
Handling Forms & JSON Data
Install Body Parser (Optional, built-in in Express 4.16+)
Parse Form Data & JSON Requests
Handling Form Submissions
Connecting Express.js with a Database
MongoDB (Using Mongoose)
Install Mongoose
Connect to MongoDB
Building a REST API with Express.js
Create a Simple API
Real-time Apps with Socket.io
Install Socket.io
Simple WebSocket Chat App
Conclusion
Node.js & Express.js are powerful tools for building scalable, fast, and efficient backend applications. Whether you're creating REST APIs, real-time apps, or full-stack projects, they provide everything you need.
Last updated
Was this helpful?