Learn Express.js Β· 1/14

Introduction to Express.js & Setup

7 min read

Introduction to Express.js & Setup πŸš€

Welcome, aspiring web developer! You're about to embark on a journey into the world of Express.js, a nifty framework that makes building web applications with Node.js a whole lot smoother. Think of this guide as your friendly companion, here to demystify the concepts and get you building cool stuff, fast.

1. The 'Why' Before the 'How': Node.js vs Express πŸ€”

The Problem: Imagine you're building a house (your web application) from scratch. You have all the raw materials: wood, nails, and tools (that's your Node.js). Node.js is a powerful JavaScript runtime that lets you execute JavaScript on the server. It gives you the fundamental building blocks, like handling HTTP requests, but you have to figure out the blueprint, how to organize everything, and how to handle common tasks like routing (directing traffic to the right rooms in your house). It's a lot of work, and you might find yourself reinventing the wheel for every project.

The Solution: Express.js! Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It's like having a pre-designed blueprint and some pre-fabricated walls for your house. It doesn't build the entire house for you, but it gives you a solid structure and a set of conventions to follow, saving you a ton of time and effort. It helps you handle things like routing, middleware (we'll get to that!), and responding to requests in a much more organized way.

So, in a nutshell:

  • Node.js: The engine that runs your JavaScript code on the server.
  • Express.js: A framework built on top of Node.js to make building web applications faster and easier.

Interesting Fact: The original creator of Node.js, Ryan Dahl, initially had some reservations about frameworks like Express, advocating for a more "pure" Node.js approach. However, the developer community overwhelmingly embraced Express for its practicality and efficiency, making it the de facto standard for Node.js web development.

2. Initializing Your First Project (npm init & dependencies) πŸ“‚

Alright, enough talk, let's get our hands dirty! Before we can write any code, we need to set up our project. This is where npm (Node Package Manager) comes in. Think of npm as a giant online store for all the code packages (like Express) you might need.

Step 1: Create a Project Folder

First things first, create a new folder for your project. You can name it whatever you like, for example, my-first-express-app.

Step 2: Initialize Your Project

Open your terminal or command prompt, navigate into your new folder, and run the following command:

bash
npm init -y

This command initializes a new Node.js project. The -y flag tells npm to use the default settings, which is perfectly fine for now. This will create a file called package.json in your folder. This file is like the birth certificate of your project; it keeps track of all the important information, including the dependencies (packages) your project needs to run.

Step 3: Install Express

Now, let's install Express. In your terminal, run:

bash
npm install express

This command does two things:

  1. It downloads the Express.js package from the npm registry.
  2. It adds Express to the dependencies section of your package.json file. This is important because if you share your project with someone else, they can simply run npm install and it will automatically download all the required packages.

Your package.json file should now look something like this:

json
{
  "name": "my-first-express-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.19.2"
  }
}

Industry Practice: It's a good idea to create a .gitignore file in your project's root directory and add node_modules/ to it. The node_modules folder contains all the downloaded packages and can get quite large. By ignoring it, you prevent it from being accidentally committed to your version control system (like Git).

3. Your First Express Server: 'Hello World' πŸ‘‹

Let's write some code! Create a new file in your project folder named index.js (or whatever you set as the main entry in your package.json).

Now, add the following code to your index.js file:

javascript
// 1. Import the express library
const express = require('express');

// 2. Create an instance of the express application
const app = express();

// 3. Define a port number
const port = 3000;

// 4. Define a route for the root URL
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 5. Start the server and listen for incoming requests
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Let's break down what's happening here:

  1. const express = require('express');: We are importing the Express.js module that we installed earlier.
  2. const app = express();: We are creating an instance of the Express application. This app object is what we'll use to configure our server.
  3. const port = 3000;: We define a port number for our server to listen on. Think of a port as a specific door on your computer that your server will be listening through.
  4. app.get('/', (req, res) => { ... });: This is where we define a route.
    • app.get: This tells our server to handle GET requests. A GET request is what your browser makes when you type a URL into the address bar.
    • /: This is the path of the route. In this case, it's the root URL of our application.
    • (req, res) => { ... }: This is a callback function that gets executed when a request is made to this route. It receives two important objects:
      • req (request): This object contains all the information about the incoming request from the client (e.g., the browser).
      • res (response): This object is what we use to send a response back to the client.
    • res.send('Hello World!');: We use the send() method on the res object to send the string 'Hello World!' back to the browser.
  5. app.listen(port, () => { ... });: This starts our server and makes it listen for incoming connections on the specified port. The callback function is executed once the server is successfully started.

To run your server, go back to your terminal and execute:

bash
node index.js

You should see the message Example app listening at http://localhost:3000 in your console. Now, open your web browser and navigate to http://localhost:3000. You should see the glorious text "Hello World!". πŸŽ‰

4. Understanding the Event Loop & Asynchronous Flow πŸ”„

The Problem: Imagine you're a librarian at a very busy library. You have people constantly coming to you with requests: "Can you find this book?", "Can you check out these books?", "Where is the history section?". If you handled each request one by one, waiting for one person to finish before even acknowledging the next, the line would get incredibly long and people would get frustrated. This is what's known as "blocking" behavior.

The Solution: Asynchronous Flow and the Event Loop! Node.js operates on a single thread, but it's incredibly efficient because of its non-blocking, event-driven architecture. This is where the event loop comes in.

Think of the event loop as our super-efficient librarian. When a request comes in (like finding a book that might take a while), the librarian doesn't just stand there waiting. Instead, they take the request, give it to a library assistant (a background thread), and immediately start helping the next person in line. Once the assistant finds the book, they bring it back to the librarian, who then gives it to the person who originally requested it.

In the context of your Express server:

  • Requests are like the people coming to the librarian.
  • The Event Loop is the librarian, constantly checking for new requests.
  • Long-running tasks (like reading a file from the disk or making a database query) are like finding a book in the vast library.
  • Callback functions are what the librarian does once the book is found (sending the response back to the client).

This asynchronous model is what allows a Node.js server to handle thousands of concurrent connections without getting bogged down. It's a fundamental concept to grasp as you dive deeper into Node.js and Express development.

Under the Hood: The event loop is a constantly running process that checks a queue for pending events (like an incoming HTTP request or a completed database operation) and executes their corresponding callback functions. This is why you see so many callback functions in Node.js code!


Further Reading & References πŸ“š

Challenge

Challenge

Your task is to build a complete Express.js server from scratch. The server must be fully functional and contained within a single script.

Requirements:

  1. Import the express module.
  2. Create an instance of an Express application.
  3. Define a constant for the port number and set it to 4200.
  4. Create a route that handles GET requests to the root path (/).
  5. The route handler must send the plain text string "Welcome to the Express Server" as the response.
  6. Start the server and make it listen on the specified port.
  7. When the server starts, it should log a message to the console in the format Server is running on port 4200.

Expected result

Your submission should be a complete Node.js script that correctly sets up and runs a basic Express server. The code must:

  • Properly import the express library.
  • Instantiate the Express application.
  • Contain a app.get() method for the / route that uses res.send() to return the exact string "Welcome to the Express Server".
  • Use the app.listen() method to start the server on port 4200.
  • Include a callback function in app.listen() that logs the required startup message to the console.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.