Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to create server-side applications with ease. It is designed to facilitate scalable and efficient networking and give them a high-performance platform to work with.
In this tutorial, we will look at building a web application with Node.js – covering from setting up your development environment to building a feature-rich web application.
Setting up the Development Environment
Before we start building our web application, we must ensure that our development environment is set up correctly. Here’s how you can set up your development environment:
- Install Node.js
First, you need to install Node.js – you can visit the official website(https://nodejs.org/en/) and download the Node.js installer for your operating system.
- Install a Text Editor or Integrated Development Environment (IDE)
Next, you need a text editor or integrated development environment (IDE) to write your code. There are many options available, including Visual Studio Code(https://code.visualstudio.com/), Sublime Text(https://www.sublimetext.com/), and Atom(https://atom.io/).
- Create a New Directory for your Web Application
Now that you have your development environment set up, create a new directory for your web application and navigate to it in your terminal or command prompt.
- Initialize the Project with NPM
With your directory in place, you now need to initialize a new project with NPM (Node Package Manager). To do this, you need to input the following command in your terminal or command prompt:
npm init
This command will prompt you to provide details about your project, such as the project’s name, version, and description.
Once you’ve provided these details, npm will create your package.json file – this file contains information about your project and the dependencies it requires.
Setting up Basic Server with Node.js
Now that you’ve initialized your project, you can begin building your web application. The first step is to set up a basic server. Here’s how you can set up your server:
- Install the Express Framework
The Express framework is a popular choice for building web applications with Node.js. You can install the Express framework by typing the following command in your terminal or command prompt:
npm install express --save
- Create your server.js file
Now you need to create a new file in your project directory and name it server.js.
- Write your Code
With your server.js file created, it’s time to write code to set up your server. Let’s start with your code by requiring the Express framework and setting up your server to listen to incoming requests:
const express = require('express');
const app = express();
app.listen(3000, () => console.log('Server started at http://localhost:3000'));
In this code block, you require the express module and set the app variable to an instance of Express. Then, you set up your server to listen for incoming requests on port 3000 and log a message to the console to let you know that the server has started.
- Start your server
Now navigate to your project directory in your terminal or command prompt and type the following command to start your server:
node server.js
You should now be able to view your web application by navigating to http://localhost:3000 in your web browser.
Creating Routes with Express
Now that you’ve set up a basic server, you need to create routes for your web application. Here’s how you can set up routes:
- Create a new file in your project directory and name it routes.js.
-
Write your Code
With your routes.js file created, it’s time to write code to set up your routes. Let’s start with your code by requiring the Express framework and setting up your routes:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Hello World!');
});
module.exports = router;
In this code block, you have required the express module and set up your routes using the router object. Next, you have set up a GET request to handle the root path of your web application – when a user navigates to the root path, the callback function in this code block will execute, and the response that is sent to the client will be ‘Hello World!’.
- Integrate Your Routes with Server
Now that you’ve created your routes, you need to integrate them with your server. You can do this by requiring your routes.js file in your server.js file and using the app.use()
method to apply your routes:
const express = require('express');
const routes = require('./routes');
const app = express();
app.use('/', routes);
app.listen(3000, () => console.log('Server started at http://localhost:3000'));
In this code block, you have required your routes.js file and used the app.use()
method to apply your routes to the root path of your web application.
- Test Your Routes
With your routes set up, it’s time to test them. Start your server with the node server.js
command, and then navigate to http://localhost:3000 in your web browser – if everything is set up correctly, you should see the ‘Hello World!’ message display on your webpage.
Building a Web Application with Node.js
Now that you’ve created routes and set up your server, it’s time to build a feature-rich web application. Here’s how you can build your web application:
- Install EJS
EJS is a popular templating engine that lets you generate HTML markup with plain JavaScript. You can install EJS by typing the following command in your terminal or command prompt:
npm install ejs --save
- Create a Views Directory
With EJS installed, you need to create a new directory in your project directory and name it views – this directory will store your EJS templates.
- Create an EJS Template
Create a new file in your views directory and name it index.ejs. In this file, you need to write code that generates your HTML markup. Here’s an example:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome to <%= title %></h1>
<ul>
<% for(let i = 0; i < names.length; i++) { %>
<li><%= names[i] %></li>
<% } %>
</ul>
</body>
</html>
In this code block, you have set up an HTML page with a dynamic title and a list of names. The title and names are dynamically generated with the EJS templating engine.
- Update Your Routes
With your EJS template created, you need to update your routes to render the template. Here’s how you can do it:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
const data = {
title: 'My Website',
names: ['John', 'Jane', 'Doe'],
};
res.render('index', data);
});
module.exports = router;
In this code block, you have created a data object with a title and an array of names. Next, you have passed the index.ejs template and the data object to the res.render()
method – this method renders your EJS template with the data passed in and generates the HTML markup.
- Test Your Web Application
With your web application built, it’s time to test it. Start your server with the node server.js
command, and then navigate to http://localhost:3000 in your web browser – if everything is set up correctly, you should see your web application display on your webpage.
Conclusion
In this tutorial, we have looked at building a web application with Node.js – from setting up your development environment to building a feature-rich web application. We covered how to set up a server with Express, create routes, and generate HTML markup with the EJS templating engine – giving you a solid foundation to build on.
With Node.js and its many libraries and frameworks, you can build highly performant and scalable web applications in no time. So go ahead and give it a try – and feel free to reach out to the community if you need any help. Happy Coding!