Building a Server with Node.js on Port 4000: A Beginner's Guide

Rudra DesaiRudra Desai
2 min read

Are you ready to dive into the world of server-side programming with Node.js? In this guide, we'll walk through the steps of creating a simple server using Node.js and running it on port 4000. Let's get started!Getting StartedFirst things first, ensure you have Node.js installed on your system. You can download and install it from the official Node.js website (https://nodejs.org/).Setting Up Your ProjectCreate a new directory for your project and navigate into it using your command line interface. Then, initialize a new Node.js project by running:

"npm init -y"

This command will create a package.json file with default values.

Installing Dependencies

"npm install express"

Creating Your Server

Now, let's create a file named server.js in your project directory. This file will contain the code for our server. Open server.js in your favorite text editor and add the following code:

const express = require('express');

const app = express();

const port = 4000;

// Define a route

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

res.send('Hello, world!');

});

// Start the server

app.listen(port, () => {

console.log(`Server is running on port ${port}`);

});

Running Your Server

To start your server, run the following command in your terminal within your project directory:

"node server.js"

You should see the message "Server is running on port 4000" in your terminal, indicating that your server is now running.

Testing Your Server

Open your web browser and navigate to http://localhost:4000. You should see the text "Hello, world!" displayed in the browser, confirming that your server is up and running.

Conclusion

Congratulations! You've successfully built a simple server using Node.js and Express, running on port 4000. This is just the beginning of what you can do with Node.js, so feel free to explore further and build more complex applications. Happy coding!

1
Subscribe to my newsletter

Read articles from Rudra Desai directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rudra Desai
Rudra Desai