While learning node.js I read that
We use require directive to load http module and store returned HTTP
instance into http variable as follows −
var http = require("http");
I want to know what does http
module means ?
HTTP is a protocol for fetching resources such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser.
Thus, var http = require('http') is just to import the built-in http module, so that we can create http server which will respond to our requests. After importing the module, a server can be created by using the createServer() method offered by http module. var server = http. createServer(handleRequest);
“Require” is built-in with NodeJS require is typically used with NodeJS to read and execute CommonJS modules. These modules can be either built-in modules like http or custom-written modules. With require , you can include them in your JavaScript files and use their functions and variables.
createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.
An easy way to think of modules is to think of them as libraries. They add additional functionality into your application based on which modules you decide to import and use.
The http module is most beneficial in nodejs when you need to make a request over the hyper text transfer protocol. For example, if you want to send a post
request or get
request to a specific url, you can't use something like ajax
which only works in the frontend. You will need to use the http module
in order to do something like this (or use a related module but http is one of the more common ones).
The http module also has additional functionality such as creating a server or managing sockets. I recommend looking at the api for specific details- but if you are doing anything related to sending data over http: the http module is definitely worth looking into.
The easiest way to explain will be to tell you that the http module enables you to make requests to servers. If you however will like to get a proper understanding of how the node http module works then I will refer you to the documentation here https://nodejs.org/api/http.html
The documentation might seem be a bit heavy if you do not like to read but it does go very deep which is why I recommend it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With