Nearby lessons

11 of 21

🌐 HTTP Module in Node.js

📌 What is HTTP Module?

JavaScript is primarily a client-side scripting language, whereas Node.js allows JavaScript to run on the server side.

JavaScript Flow: Application → Web Browser → Client

Node.js Flow: Application → Server

What is a Module in Node.js?

A module is a chunk of code in an external file that performs a specific task or function. Node modules allow re-use of code in your Node applications.

In some ways, modules are similar to classes in languages like C# or Java.

Default Port Numbers

Node.js applications often listen on port 3000 or 4000, but these are just conventions. You can choose any port.

⚡ HTTP Module in Node.js

  • Node.js has a built-in HTTP module that allows transferring data over HTTP.
  • It provides utilities to create HTTP servers and clients.
  • It enables handling of HTTP requests and responses.
  • Use http.createServer() to create a server that listens for incoming requests.

📝 Example 1 - Creating a Simple HTTP Server

Node.js Environment
RUNTIME ACTIVE
var http = require('http');

const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/plain');
  res.write('Response From Server.. Codings Points');
  res.end();
});

server.listen(3000, "localhost", () => {
  console.log("Server Running At http://localhost:3000");
});
Terminal Output
Live Output Preview

📝 Example 2 - Alternative Syntax

Node.js Environment
RUNTIME ACTIVE
var http = require('http');

http.createServer(function(req, res){
  res.setHeader('Content-Type','text/plain');
  res.write('Response From Server..Codings Points');
  res.end();
}).listen(3000, "localhost", () => {
  console.log("Server Running At http://localhost:3000");
});
Terminal Output
Live Output Preview

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!URL Module in Node.js