No history yet

Introduction to Node.js and Express.js

JavaScript on the Server

For a long time, JavaScript lived exclusively in the web browser. It was used to make web pages interactive. That changed with Node.js, a runtime environment that allows you to run JavaScript code directly on a server.

Node.js lets you use the same language for both the front-end (what the user sees) and the back-end (the server logic), which simplifies web development.

The real power of Node.js lies in its architecture. It's built to be asynchronous and event-driven. This means it can handle many tasks at once without waiting for each one to finish. Think of a busy restaurant. A traditional server might take one order, go to the kitchen, wait for the food, deliver it, and only then move to the next table. This is blocking—one task blocks all others.

A Node.js server is like a more efficient waiter. It takes an order from table one, gives it to the kitchen, then immediately takes an order from table two, and so on. When the food for table one is ready, the kitchen sends out a notification (an "event"), and the waiter delivers it. This non-blocking approach allows Node.js to handle thousands of simultaneous connections with minimal resources, making it perfect for building APIs and real-time applications.

Setting Up Your Project

Before you can write any code, you need to set up your environment. This involves installing Node.js and creating a project folder.

First, download and install Node.js from its official website. The installation includes npm (Node Package Manager), a tool for managing project dependencies, which are libraries of code that your project will use.

Once Node.js is installed, open your terminal or command prompt, create a new directory for your project, and navigate into it. Then, run the following command to initialize your project:

npm init -y

This command creates a package.json file. This file acts as a manifest for your project, keeping track of its details and dependencies. Now, let's add our first dependency: Express.js.

Node.js frameworks (Adonis.js, NestJS, Express) for API-only applications

Express.js is a minimal and flexible Node.js framework that makes building web applications and APIs much simpler. To install it, run this command in your terminal:

npm install express

Npm will download Express.js and add it to a node_modules folder and list it as a dependency in your package.json file.

Creating a Basic Server

With the setup complete, you can create a simple web server. Create a new file in your project directory named index.js and add the following code.

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

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

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

// 4. Start the server and listen for connections on the specified port
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

This code does four things:

  1. It imports the Express framework.
  2. It creates a new Express application, which we assign to the app variable.
  3. It specifies that the server should listen on port 3000.
  4. It starts the server. The function inside app.listen is a callback that runs once the server is successfully started, printing a confirmation message to the console.

To run your server, go to your terminal and execute the file using Node.js:

node index.js

If you see the confirmation message, your server is running! If you open a web browser and navigate to http://localhost:3000, you'll see a message like "Cannot GET /". This is expected because we haven't told the server how to respond to requests yet.

Handling Requests and Responses

A server's main job is to listen for incoming HTTP requests and send back HTTP responses. In Express, we do this by defining routes. A route defines how the application responds to a client request to a specific endpoint, which consists of a path (like / or /about) and an HTTP method (like GET, POST, etc.).

Let's add a route to handle GET requests to the root path (/). Modify your index.js file:

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

// Route for GET requests to the root URL ('/')
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

The new app.get() method sets up the route handler. It takes two main arguments:

  • The first is the path, which is / for the homepage.
  • The second is a callback function that runs whenever a GET request is made to that path. This function receives two important objects: req (the request) and res (the response).

Inside the function, res.send('Hello, World!') tells Express to send the string "Hello, World!" back to the client as the response.

Stop your server in the terminal (with Ctrl+C) and run it again with node index.js. Now, when you visit http://localhost:3000 in your browser, you'll see the message "Hello, World!". You've just built a working web server.

Quiz Questions 1/6

What is the primary role of Node.js?

Quiz Questions 2/6

The text describes Node.js's non-blocking architecture using a restaurant analogy. Which scenario best represents this approach?

This is the first step in building a powerful backend. You now know how to create a basic server that can handle incoming web traffic.