Creating a Node.js Server with the HTTP Module:
Once we have imported the HTTP module, we can use its
createServer() method to create an HTTP server instance. This method takes a callback function as an argument, which will be executed whenever a request is made to the server. Inside the callback function, we can handle the incoming request and send back an appropriate response. Here's an example:
In the above code, we set the response status code to 200, which indicates a successful response. We also set the
Content-Type header to
text/plain and send the string "Hello, World!" as the response body. Finally, we call the
end() method to signal the end of the response.
Starting the Server:
After creating the server instance, we need to start it by listening on a specific port. We can do this using the
listen() method of the server object. Here's an example:
In the above code, we specify that our server should listen on port 3000. Once the server is started, the callback function is executed, and a message is logged to the console indicating that the server is running.
Node.js, with its built-in HTTP module, provides a convenient way to create and manage servers for handling HTTP requests and responses. By leveraging the power of Node.js and the simplicity of the HTTP module, developers can build robust and scalable web servers efficiently. Whether you’re building a small REST API or a large-scale web application, the HTTP module in Node.js is a valuable tool in your arsenal.