DEV Community

Cover image for Building a Simple Server with Node.js and Express
ibroraheem
ibroraheem

Posted on

Building a Simple Server with Node.js and Express

INTRODUCTION

Node.js has become an incredibly popular server-side JavaScript runtime, and for good reason: it's fast, scalable, and easy to use. In this tutorial, we're going to build a simple server using Node.js and Express, a popular Node.js framework that simplifies server-side development. By the end of this tutorial, you'll have a basic understanding of how to set up a server with Node.js and Express.

PREREQUISITES

  • Node.js installed on your machine

  • Basic knowledge of JavaScript

Step 1: Setting Up Your Project

Before we dive into the code, we need to set up our project. Open up your terminal and create a new directory for your project:

mkdir simple-server
cd simple-server

Enter fullscreen mode Exit fullscreen mode

Next, initialize your project by running npm init and following the prompts:

npm init
Enter fullscreen mode Exit fullscreen mode

This will create a package.json file that we'll use to manage our dependencies.

Step 2: Installing Dependencies

We're going to be using the Express framework to build our server. To install it, run:

npm install express
Enter fullscreen mode Exit fullscreen mode

This will install the latest version of Express in your project.

Step 3: Creating Your Server

Now it's time to write some code. Create a new file in your project directory called index.js. This is where we'll write our server code.

In index.js, add the following code:

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

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

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

Let's go through what this code does:

We first import the express module and create a new instance of it.
We define a route for the root of our server (/) using the app.get() method. This route responds with the string 'Hello, world!' when accessed.
Finally, we start the server listening on port 3000 using the app.listen() method.
Step 4: Running Your Server

To run your server, simply run the following command in your terminal:

node index.js
Enter fullscreen mode Exit fullscreen mode

Top comments (0)