ESC

Search on this blog

Weekly updates

Join our newsletter!

Do not worry we don't spam!

Introduction to Node.js and Express: Building Web Applications Photo:

Introduction to Node.js and Express: Building Web Applications


Node.js has become one of the most popular platforms for building web applications in recent years. Its asynchronous, event-driven architecture makes it highly scalable and well-suited for real-time applications. In this post, we will introduce Node.js and the Express web framework and show how to use them to build a basic web application.

 

What is Node.js?

Node.js is a JavaScript runtime environment built on Google Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server, enabling them to use the same programming language in both frontend and backend development.

 

Some key benefits of Node.js:

- Asynchronous and Event Driven - All APIs of Node.js library are asynchronous that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.

- Very Fast - Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.

- Single Threaded but Highly Scalable - Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.

- No Buffering - Node.js applications never buffer any data. These applications simply output the data in chunks.

What is Express?

Express is a fast, minimal and flexible Node.js web application framework that provides robust set of features for web and mobile applications. With a myriad of HTTP utility methods and middleware, creating a robust API is quick and easy.

Some key features of Express include:

- Route handlers for requests with different HTTP verbs at different URL paths.
- Integrated view system for rendering templates.
- Ability to configure middleware functions.
- Environment-based configuration for deployment.
- Helper methods for routing, redirects, cookie handling, etc.

Together, Node.js and Express provide a lightweight platform for building fast, scalable server-side applications.

 

Building a Simple Web App with Node.js and Express

To demonstrate the basic concepts of Node.js and Express, we'll build a very simple web application that displays a list of random user data.

The app will have two routes:

1. Home page route (/) - Serves an HTML page displaying the user data
2. API route (/api/users) - Serves the user data as JSON

Here are the steps to build the app:

1. Initialize a Node.js project

# Initialize npm 
npm init
# Install express
npm install express
```
 
2. Install the EJS template engine

# Enable using .ejs files for templating
npm install ejs

 

3. Create an index.ejs file


This will be the homepage template that displays the user data.

 

4. Create an app.js file 


This will contain our Express application logic.


// Require the express module
const express = require('express');
// Create the express app
const app = express();
// Set EJS as the view engine 
app.set('view engine', 'ejs');
// Define routes
app.get('/', function(req, res) {
 // Render the index template
 res.render('index'); 
});
// Listen on port 5000
app.listen(5000); 
 
5. Generate random user data


We'll add some code to generate random user data and pass it to the EJS templates.


// User data array
const users = [];
// Generate 5 random users
for(let i = 0; i < 5; i++) {
 users.push({
   name: randomName(),
   age: randomAge()
 });
}
// Pass data to templates
app.get('/', function(req, res) {
 res.render('index', {
   users: users
 });
});

 

6. Display user data on homepage

Our index.ejs template can display the user data using EJS tags:

html
<h1>Random Users</h1>
<ul>
 <% for(let user of users) { %>
   <li><%= user.name %> - <%= user.age %></li>  
 <% } %>
</ul>

 

7. Create API route to serve JSON

We can easily add another route to serve JSON data:


app.get('/api/users', function(req, res) {
 res.json(users);
});

That completes our simple Node.js + Express web app! The app serves an HTML page displaying random user data as well as a JSON API route.

To run the app:


node app.js

The homepage should now display at http://localhost:5000 and the API data at http://localhost:5000/api/users.

Conclusion

We covered a simple example of using Node.js and Express to build a web application. Some next steps from here:

- Add a database to persist user data.
- Implement user authentication.
- Build out the UI using a frontend framework like React.
- Containerize the app with Docker for easy deployment.

The Node + Express ecosystem provides a fantastic starting point for server-side applications. With robust tooling and extensive middleware available, building production-ready apps is simple and quick!

Next Article
Getting Started with React.js: A Comprehensive Guide
Getting Started with React.js: A Comprehensive Guide

Related to this topic: