Node.js Http Module

Http Module is Node.js built-in module.Which allows Node.js to transfer data over the HTTP (Hyper Text Transfer Protocol).

How to use HTTP module in Node.js

To include the HTTP module in Node.js,require() method is used.

var http = require('http');

How to Include Node.js Modules

To inculde Node.js module, use the require() function with the name of the module as given below.

var http = require('http');

Create Web Server in Node.js

We can Create server from HTTP module,that listens to server ports and gives a response back to the client. createServer() method is used to create an server.

var http = require('http'); var http = require('http'); //create a server http.createServer(function (request, response) { res.write('Hello Node.js Users!'); //response to the client res.end(); //end the response }).listen(4004); //the server object listens on port 4004

Add an HTTP Header

If Response from HTTP server is supposed to be displayed as HTML,then you should use HTTP header with "text/html" content type like below.

var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); // text/html type content type. res.write('Hello Node.js Users!'); //response to the client res.end(); }).listen(4004);