Create Server

Following script is considerd as common.js module management system. every script that uses require function is common.js module.

// require function is used to add any dependency/modules in our script, either its build in or installed via npm
// http is build in module to create server
const http = require("http");

// createServer function is use to create server, createServer function get invoked on each request. req object and res object. .end method writes back the data.
const server = http.createServer((req, res) => {
  res.end("Hello World\n");
});
// createServer creates the server but listen method activates and keep the process running.
server.listen(4242, () => {
  console.log("Server is running...");
});

Node also supports ECMAScript module management system. this could be done by name the file with .mjs extension, or setting thw whole project for ECMAScript module management system.

file name hello-world.mjs

import http from "http";
const server = http.createServer((req, res) => {
  res.end("Hello World\n");
});
server.listen(4242, () => {
  console.log("Server is running...");
});

or we can named import, means only import the function that script uses.

import { createServer } from "http";
const server = createServer((req, res) => {
  res.end("Hello World\n");
});
server.listen(4242, () => {
  console.log("Server is running...");
});
Next