Express

Open the terminal and run the following command at the root of the project.

npm init -y

The command will create a package.json file inside the root folder. By convention, every Node application (package) has a package.json file at its root folder. We have seen this file before inside React applications. Recall this file holds metadata relevant to the project. It is also used, by NPM, for managing the project's dependencies, scripts, version, and a lot more.

Next, install Express.

npm install express

Notice three changes as a result of installing Express:

  1. Express is added as a dependency to package.json.
  2. The node_modules folder is added to the root directory. Make sure to exclude this folder from your Git repository.
  3. A package-lock.json is added to the root of your project.

You are familiar with all this, as you have seen them in previous chapters.

Here is a minimal Express application:

// index.js file
const express = require("express");
const app = express();
const port = 5000;

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

app.listen(port, () => {
  console.log(`Express app listening at http://localhost:${port}`);
});

Go to the terminal and run node index.js. You will see the following message printed in the terminal:

Express app listening at http://localhost:5000

While the Express app is running, open your browser and go to http://localhost:5000/. You will see the "Hello Express" message!

Recall: to stop the app, you must halt the process by pressing Ctrl + C.

Let's explore the code:

  • The require("express") returns a function we capture in the express variable.
  • This function returns an object we capture in the app variable by invoking express().
  • The app object has methods for handling HTTP requests, among other things.
  • The app.get() handles an HTTP Get request.
  • The first argument to app.get() is the path or API endpoint address.
  • The second argument to app.get() is a callback function. This function is called every time client visits the API endpoint.
  • The call-back function receives two arguments. The req and resp bindings are objects representing the incoming and outgoing data.
  • The app.listen() binds and listens for connections on the specified port. This method is identical to Node's http.Server.listen(). It optionally takes a second argument, a call-back function, which I've used to simply print a message to the terminal.

The application we've built here with Express is identical to the one we had made earlier with Node's HTTP Module. Express is built on top of Node's HTTP module, but it adds a ton of additional functionality to it. Express provides a clean interface to build HTTP server applications. It offers many utilities, takes care of nuances under the hood, and allows for many other packages to be added as middleware to further the functionality of Express and your server application.