No history yet

Introduction to Node.js and Express.js

Node.js: JavaScript on the Server

For a long time, JavaScript lived exclusively in the web browser. It was the language for making web pages interactive. Node.js changed that. It's a runtime environment that allows you to run JavaScript code on a server, outside of a browser.

This means you can use the same language you might already know from front-end development to build the back-end of your applications. Node.js is particularly good at handling many connections at once, which makes it great for chat apps, streaming services, and other real-time applications.

The Non-Blocking Waiter

The secret to Node.js's efficiency is its non-blocking I/O (Input/Output) model. I/O operations are things like reading a file from the disk, making a network request to another service, or querying a database. These tasks can be slow.

Imagine a restaurant with two types of waiters.

The Blocking Waiter: Takes an order from Table 1, walks it to the kitchen, and waits there until the food is ready. Only after delivering the food to Table 1 does he move on to Table 2. The other tables have to wait, even if they're just ready to order a drink.

The Non-Blocking Waiter (Node.js): Takes an order from Table 1 and gives it to the kitchen. Instead of waiting, she immediately moves to Table 2 to take their order, then Table 3, and so on. When the kitchen finishes a dish, they ring a bell, and she picks it up and delivers it. She handles many tables at once without getting stuck waiting.

Node.js works like the non-blocking waiter. It can handle a new request while waiting for a previous, slower operation to complete. This is part of its event-driven architecture. When a task is finished, Node.js gets a notification (an event) and executes a callback function to handle the result.

Enter Express.js

While you can build a server using only Node.js, it can be a bit repetitive. You'd have to manually handle the details of every HTTP request, like parsing the URL and headers. This is where a framework comes in handy.

Framework

noun

A pre-written set of code and tools that provides a standard way to build applications. It handles common tasks so developers can focus on the unique logic of their app.

Express.js is the most popular web framework for Node.js. It's described as "minimal and flexible," meaning it provides a thin layer of fundamental web application features without hiding the parts of Node.js you already know. It simplifies tasks like routing, which is figuring out how to respond to a user's request for a specific URL.

Your First Express App

First, you'll need to install Node.js on your computer. You can download it from the official Node.js website. This also installs npm (Node Package Manager), which is used to manage third-party libraries, like Express.

Once Node.js is installed, create a new folder for your project, open it in your terminal, and run this command to initialize a new Node project:

npm init -y

This creates a package.json file, which keeps track of your project's details and its dependencies. Now, install Express:

npm install express

Create a file named app.js and add the following code. This sets up a simple server that listens for requests.

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

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

// 3. Define the port the server will run on
const port = 3000;

// 4. Define a route
// When a GET request is made to the homepage ('/'),
// respond with 'Hello, World!'
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// 5. Start the server
app.listen(port, () => {
  console.log(`Server is listening on http://localhost:${port}`);
});

To run your server, go to your terminal and type:

node app.js

Now, if you open a web browser and go to http://localhost:3000, you'll see the text "Hello, World!" on the page. You've just created your first web server with Express.

Understanding Routing

The core of the server is the routing. A route defines how the application responds to a client request to a specific endpoint, which consists of a URL path and an HTTP request method (like GET, POST, etc.).

Let's look at the route from our example:

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

Here's what each part does:

  • app: The Express application instance.
  • .get: The HTTP method. This route only responds to GET requests, which are what browsers use when you type a URL.
  • '/': The path. A single slash represents the root or homepage of the site.
  • (req, res) => { ... }: This is the handler function, which is called when the route is matched. It receives two important objects: req (the request) and res (the response).
  • res.send(...): This sends a response back to the client.

You can easily add more routes. For example, to handle a request for a /about page, you would add:

app.get('/about', (req, res) => {
  res.send('This is the about page.');
});

With this simple mechanism, Express provides a powerful way to build the structure of a web application or API.

Quiz Questions 1/5

What is the primary purpose of Node.js?

Quiz Questions 2/5

Which feature is key to Node.js's efficiency in handling many simultaneous connections, especially for real-time applications?

These are the first steps into building with Node.js and Express. You've learned how Node's architecture makes it efficient and how Express simplifies the process of building a server.