Web Designing 2 — Study Notes

Unit 05

Node.js — Runtime, Components, Servers & File System

6 Questions 6 Marks Each Web Designing 2
01
6 Marks Question

Node.js — Concept, Working, and Features

Node.js is a powerful platform used for building scalable network applications. It allows developers to use JavaScript to write server-side code, which was traditionally only used for client-side scripting in web browsers.

Concept of Node.js

Runtime Environment
Node.js is not a programming language or a framework — it is an open-source, cross-platform runtime environment.
V8 Engine
It is built on Google Chrome's JavaScript V8 runtime, which is designed to execute JavaScript code very quickly.
Server-Side JavaScript
Its primary concept is to run JavaScript outside the browser, allowing for the development of server-side and networking applications.
Composition
It is essentially a combination of a runtime environment and a rich library of various JavaScript modules.

Working of Node.js

Node.js operates differently than traditional web-serving techniques:

Event-Driven and Non-blocking
It uses an event-driven, non-blocking I/O model. The server does not wait for an API to return data; it moves to the next API immediately.
Single-Threaded
Node.js follows a "Single Threaded Event Loop" model, allowing it to handle many concurrent client requests without creating multiple threads for each.
Efficiency
Because it never waits for data (non-blocking), it is extremely lightweight and efficient — perfect for data-intensive real-time applications.

Key Features of Node.js

AsynchronousAll APIs are non-blocking; the server never waits before moving on.
FastBuilt on V8 engine — very fast in code execution.
No BufferingApplications never buffer data; they output data in chunks.
ScalableEvent mechanism makes the server highly scalable vs traditional thread-based servers.
Cross-PlatformRuns seamlessly on Windows, Linux, and OS X.
Conclusion Node.js is a non-blocking, event-driven runtime environment that allows JavaScript to run on the server side, making it highly efficient and scalable for real-time web applications.
02
6 Marks Question

Components of Node.js

Node.js is composed of several key components that work together to provide a high-performance, asynchronous environment for executing JavaScript on the server side.

V8 EngineV8 JavaScript Engine
Developed by Google for Chrome, this is the core component that compiles JavaScript code directly into native machine code. It is responsible for the high speed and efficiency of Node.js applications.
LibuvLibuv — Event Loop & Thread Pool
A multi-platform support library focused on asynchronous I/O. It provides the Event Loop — the heart of Node.js — which manages all asynchronous operations by listening for events and triggering callback functions. Also contains a Thread Pool to handle heavy tasks like file system operations.
ModulesStandard Library — Node.js Modules
Node.js includes a rich set of built-in JavaScript modules that simplify web development:
  • HTTP/HTTPS — For creating web servers and handling requests.
  • FS (File System) — For reading, writing, and deleting files.
  • Path — For handling and transforming file paths.
  • URL — For parsing and resolving URL strings.
BindingsNode.js API / Bindings
These are interfaces (wrappers) that allow JavaScript code to communicate with the lower-level C/C++ components like V8 and Libuv. This layer ensures JavaScript developers can access powerful system features without needing to write C++ code.
NPMNPM — Node Package Manager
NPM is a critical component that serves as the official package manager for Node.js. It allows developers to share, reuse, and manage third-party libraries and dependencies easily.
REPLREPL — Read-Eval-Print-Loop
A computer environment (like a Windows console or Unix/Linux shell) where you can enter Node.js commands and see immediate results. It is used for testing simple pieces of code and debugging.
Conclusion Node.js is powered by the V8 engine for speed, Libuv for async I/O, a rich standard library, API bindings, NPM for package management, and REPL for interactive testing.
03
6 Marks Question

Required Modules — Creating a Server and Handling Request-Response

In Node.js, the http module is a core built-in module that allows Node.js to transfer data over the HTTP protocol. It is primarily used to create a web server that listens to server ports and gives a response back to the client.

Creating a Server — http.createServer()

The http.createServer() method is used to create an instance of an HTTP server.

Syntax
var http = require('http');

http.createServer(function (req, res) {
  // Logic goes here
}).listen(8080);
Working: This method takes a function as an argument executed every time someone accesses the computer on port 8080. The .listen() method specifies the port on which the server listens for incoming requests.

The Request Object (req)

The req (Request) argument represents the request from the client — an object containing information about the incoming data from the web browser.

  • Purpose: Used to get information such as the URL, headers, and data sent by the client.
  • Example: req.url holds the part of the URL after the domain. Visiting localhost:8080/summer makes req.url return /summer.

The Response Object (res)

The res (Response) argument represents the response the HTTP server sends back when it receives a request.

res.writeHead()Sends a status code and HTTP headers. E.g., status 200 with Content-Type text/html.
res.write()Writes the actual body text/content to be displayed on the webpage.
res.end()Mandatory — signals all response headers and body have been sent; message is complete.

Summary Example

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'}); // Header
  res.write('Hello World!');                           // Body
  res.end();                                           // Finalize
}).listen(8080);
The Request is triggered when a user enters the URL in a browser. The Response is the "Hello World!" text sent back to the user's screen.
Conclusion The http module enables Node.js to act as a web server. createServer() handles incoming requests, while req and res objects manage request data and send responses back to the client.
04
6 Marks Question

require() Function and User-Defined Modules

Part 1 — require()

The require() Function

In Node.js, the require() function is a built-in tool used to include (import) code from other files or modules into your current file. It reads a JavaScript file, executes it, and allows you to use its functions and variables — preventing you from writing all code in one single file.

Syntax
var myModule = require('module_name_or_path');

Types of Modules it Can Load

CoreBuilt-in Node.js tools — e.g., require('http')
Third-PartyDownloaded packages — e.g., require('express')
User-DefinedCustom files created by the programmer using a relative path.
Part 2 — User-Defined Modules

User-Defined Modules

User-defined modules are custom JavaScript files created by the developer. They help keep the project organized, clean, and reusable. Creating and using a module involves two steps:

  • Step 1 — Exporting: To make a function available to other files, publish it using the module.exports keyword.
  • Step 2 — Importing: To use that custom file, use require() with the exact file path (using ./ for files in the same folder).

Example

math.js — Creating the Module
// Create a simple addition function
var addNumbers = function(a, b) {
    return a + b;
};

// Export it so other files can use it
module.exports = addNumbers;
app.js — Using the Module
// Require the local module
var mathModule = require('./math.js');

// Use the function
var result = mathModule(5, 10);

// Output: 15
console.log(result);
Conclusion The require() function imports code from core, third-party, or user-defined modules. User-defined modules use module.exports to share functions and require('./path') to import them, keeping code clean and reusable.
05
6 Marks Question

Node.js as a Web Server

Node.js can be used to create web servers that handle HTTP requests and responses. It uses a non-blocking, event-driven architecture, making it efficient for handling multiple client requests simultaneously.

createServer() Method

The createServer() method is used to create an HTTP server in Node.js. It is provided by the http module and takes a callback function with req and res objects. The server listens to client requests and sends responses accordingly.

Syntax
http.createServer(function (req, res) {
    // handle request and response
});

writeHead() Method

The writeHead() method sends HTTP response headers — specifying the status code and content type. It must be called before sending the response body.

Syntax
res.writeHead(statusCode, { 'Content-Type': 'text/html' });
Example — 200 means successful response
res.writeHead(200, { 'Content-Type': 'text/html' });

Reading Query String

A query string contains data sent in the URL after ?. Node.js uses the url module to read query strings.

Example URL
http://localhost:8080/?name=John&age=21
Code
var url = require('url');
var q = url.parse(req.url, true).query;
// q.name → "John"
// q.age  → "21"

Splitting Query String

When using url.parse(req.url, true), Node.js automatically converts the query string into a key-value object.

Example
var qdata = url.parse(req.url, true).query;

// Input:  name=Faizan&age=20
// Result:
{
  name: "Faizan",
  age:  "20"
}
Conclusion Node.js acts as a powerful web server using createServer() to handle requests, writeHead() to send responses, and the url module to read and split query strings efficiently.
06
6 Marks Question

File System (fs) Module in Node.js

The fs module stands for File System. It is a built-in tool in Node.js that allows you to work with files on your computer. Since it is built-in, you don't need to install anything — just require it.

Common Uses of the fs Module

ReadGet the content out of a file to display or use it.
CreateCreate new files on the file system.
UpdateAppend or overwrite content in existing files.
DeleteRemove files from the computer.
RenameChange the name of an existing file.

Reading a File — fs.readFile()

Used to get the content out of a file to display it or use it. 'utf8' tells Node.js to read the file as human-readable text.

var fs = require('fs');

fs.readFile('message.txt', 'utf8', function(err, data) {
  if (err) throw err;
  console.log(data); // Prints the file content
});

Creating / Writing a File — fs.writeFile()

Creates a new file. If the file already exists, it replaces the old content with the new content.

var fs = require('fs');

fs.writeFile('mynewfile.txt', 'Hello students!', function (err) {
  if (err) throw err;
  console.log('File Created!');
});

Appending to a File — fs.appendFile()

Adds new content at the end of an existing file without deleting the old content.

fs.appendFile('mynewfile.txt', ' This is extra text.', function (err) {
  if (err) throw err;
  console.log('Updated!');
});

Deleting and Renaming Files

fs.unlink()Removes a file from the computer.
fs.unlink('filetodelete.txt', callback);
fs.rename()Changes the name of a file.
fs.rename('old.txt', 'new.txt', callback);
Why Asynchronous? Node.js starts reading the file and immediately moves on to the next task. When the file finishes reading, it "calls back" and shows you the result — keeping the program fast and preventing it from "freezing" while waiting for a large file.
Conclusion The fs module provides methods to read, write, append, delete, and rename files asynchronously, making all file operations fast and non-blocking in Node.js.