Node Js (Diving Deep into the Internals)

So recently I started diving deep on how does Node Js actually works . So the first question that arises what the heck is this Node Js.

  • Nodejs is a Javascript Runtime Environment that helps us in executing and running our javascript code on the server

Javascript Runtime Environment

The JavaScript Runtime Environment can be considered as a container that provides everything necessary to execute JavaScript code. It includes a JavaScript engine that parses and compiles the code into machine code for execution. Additionally, the environment contains APIs and mechanisms like the event loop to handle asynchronous behaviour and external interactions.

JavaScript is a high-level language that needs to be interpreted or compiled by the JavaScript engine to machine code for execution. While JavaScript itself cannot directly access system internals such as the operating system, kernel features, or file system, Node.js enables these interactions through lower-level languages like C++ and the libuv library, which provide the necessary system-level capabilities.

So what exactly happens when u create a server using Nodejs?

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World!');
});

server.listen(3000, () => {
  console.log('Server running at <http://localhost:3000/>');
});
  1. The first step is requiring the HTTP module from Node.js's core, which provides utilities for creating an HTTP server. This module allows us to create a server that can listen for and handle incoming requests over the network.

  2. When we call http.createServer, it creates an HTTP server that listens for incoming requests on a specific port. Internally, Node.js uses its network APIs to listen for connections at the system's network interface, but the abstraction presented by createServer is focused on handling HTTP traffic. Once a request is received, Node.js invokes the provided callback function.

  3. When a client makes a request, Node.js automatically generates two objects: the req (incoming request) and res (outgoing response). These are representations of the HTTP request and response streams, created by Node.js, and are passed as arguments to the callback function. These objects are provided as JavaScript objects, giving us access to HTTP headers, request body, and response handling methods.

HTTP listen method
When we open a channel for incoming requests, they can arrive at any port between 0 and 65,536. To handle this, when we invoke the http.createServer function, it automatically creates an instance of the HTTP server. This instance provides a listen method, which allows us to specify the exact port number we want the server to listen on, ensuring that it handles incoming requests on the desired port.