Creating a Hello World Server with Node.js and HTTP Protocol

Posted by

Hello World Server Using Node.js Http Protocol

Hello World Server Using Node.js Http Protocol

If you’re new to Node.js and want to learn how to create a simple server using the Http protocol, you’ve come to the right place. In this article, we’ll walk you through the steps of setting up and running a basic “Hello World” server using Node.js.

Prerequisites

Before you begin, make sure you have Node.js installed on your machine. You can download it from the official Node.js website.

Setting up the Server

First, create a new directory for your project and navigate into it using the terminal. Then, create a new file called server.js and open it in your code editor.


  const http = require('http');

  const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, world!n');
  });

  const PORT = process.env.PORT || 3000;

  server.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
  });
  

In this code, we are using Node.js’s built-in http module to create a simple server that listens for incoming requests and responds with a “Hello, world!” message. The server listens on port 3000 by default, but you can change it by setting the PORT variable to a different value.

Running the Server

Once you’ve set up the server, save the server.js file and return to the terminal. Run the following command to start the server:


  node server.js
  

Now, open your web browser and navigate to http://localhost:3000. You should see a “Hello, world!” message displayed on the screen. Congratulations, you’ve successfully created and run a simple Node.js server using the Http protocol!

Conclusion

Creating a basic server using Node.js’s Http protocol is a fundamental skill for any web developer. With just a few lines of code, you can start building your own web applications and APIs. We hope this article has provided you with a helpful introduction to getting started with Node.js servers. Happy coding!