How to Create a Basic Web Server in Node.js

Node.js has become one of the most popular choices for server-side development since its initial release over a decade ago. Although still relatively new compared to PHP and other backend technologies, it has been widely adopted by tech giants like LinkedIn, PayPal, Netflix, etc.

This article will teach you how to build and run your own web server with Node.js and the Express.js web framework.

Technologies and software involved

Node.js is a JavaScript runtime built on Chrome’s V8 engine that lets you run JavaScript code outside of the browser. Traditionally, the JavaScript programming language is used to manipulate the document object model (DOM), adding interactivity to websites.

For this reason, JavaScript code has been restricted to run only in the browser since the DOM only exists on web pages. With Node.js, you can run JavaScript in the command line and on servers. Therefore, it is essential to install Node.js and npm on your machine before starting.

On the other hand, Express.js is a minimalist web framework that has become the de facto backend framework for Node.js. However, Express.js is not a requirement. You can still use the http Node.js module to build your server. Express.js is built on top of the http module and provides a simpler API with all necessary configurations.

Build a web server

To better organize your code, you can start by creating a folder where all the files and dependencies will reside. As Express.js is not a built-in Node.js module, you will need to install it using npm.

USE VIDEO OF THE DAY

Read more: What is npm?

To install the Express.js package, run the command npm install express on your terminal or command prompt. Make sure you are in the project directory before installing.


Install express through npm

Once done, you can open the folder using a text editor or IDE of your choice and create a new file named server.js. To use the Express.js package, you must first import it and create an instance of it in the server.js file like this:

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

The main purpose of a web server is to respond to requests from different routes with the appropriate handler function. This code handles all GET requests made to the root (“/”) path and responds with “Hello World!”


app.get('/', (req, res) => {
res.send('

Hello World

');
});

Likewise, you can display dynamic content and perform other operations depending on the path and type of query you are making. This can be done using the route parameters, indicated by the semicolon : before the parameter.

app.get('/:name', (req, res) => {
res.send(`

Welcome to ${req.params.name}!

`);
};

In the two examples above, the first line represents the use of the .to have() method of Express.js that takes 2 parameters: the endpoint or route, and a callback handler function that takes request and response objects as parameters. These 2 parameters are automatically sent when you make a request.

In the second line, the answer is made by the .to send() method on the response object. Inside the parenthesis, you can enter the text or the HTML code of your choice. In the case of dynamic routes, the access req.params.name (since you used /:Last name) of the request object will return the value of the dynamic route parameter (Last name in this case.)

Finally, to start listening for incoming requests on a port, you can use the .Listen() method that takes the port number and an optional callback function to execute on successful execution.

app.listen(5000, console.log('Server is running on port 5000'));

I used port 5000 in the example, but you can change it to any valid port. This is all the code you need to build a basic web server with Node.js and Express.js. The same concept can be extended further to make other requests such as PUBLISH, TO PUTWhere TO ERASE to other routes. Here’s how the server.js the file will look like:


ExpressJS code for web server

Test the server

To run the code and start the server, run the node server command on your terminal or command prompt in the project directory. This will run the callback function you provided on the .Listen() method.


Express server running

To confirm that the server is working, open a web browser and visit http://localhost:5000


Express.js - root route demo

Similarly, if you are visiting a dynamic route such as http://localhost:5000/muothe second handler function will run and print:


Express.js - Dynamic Routing Demo

To stop the server, press CTRL+C under Windows or Command + C on macOS.

Node.js can do more

The popularity of JavaScript is increasing sharply as developers use it on the frontend as well as the backend. It eliminates the need to learn multiple programming languages ​​and helps you start your journey as a complete web developer using only JavaScript.

If you decide you’d rather try out Google’s programming language, building a basic web server is a great starter project.


featured image for Go web server
How to Create a Basic Web Server in Go

On your marks, get set, Golang: Start building web servers with Go.

Read more


About the Author