/

Building an HTTP Server with Node.js

Building an HTTP Server with Node.js

In this article, we will walk you through the process of building an HTTP server using Node.js. This HTTP server will serve as a basic “Hello World” application using the Node.js introductory code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const http = require('http')

const hostname = 'localhost'
const port = 3000

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

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})

Now, let’s analyze the code step by step. First, we include the http module, which is required to create an HTTP server.

The server is created by invoking the createServer method provided by the http module. We pass a callback function as an argument, which will be executed for every incoming request. This function receives two objects: a request object (http.IncomingMessage) and a response object (http.ServerResponse). These objects provide access to request details, such as headers and data, and allow us to respond to the client.

Inside the callback function, we set the status code of the response to 200 using res.statusCode = 200 to indicate a successful response.

Next, we set the Content-Type header of the response using res.setHeader('Content-Type', 'text/plain'). In this case, we’re setting it to plain text.

Finally, we close the response and send the content to the client using res.end('Hello World\n').

By running this code, the server will start listening on the specified hostname (localhost) and port (3000). You will see a console log message indicating that the server is running.

That’s it! You have successfully built a basic HTTP server using Node.js. Feel free to explore more advanced functionalities and build more complex applications using the http module.

tags: [“Node.js”, “HTTP server”, “web development”]