Program: -1
a. Write a program to show the workflow of JavaScript code executable by
creating web server in [Link].
Creating a Simple Web Server in [Link]
const http = require('node:http');
const hostname = '[Link]';
const port = 3000;
const server = [Link]((req, res) => {
[Link] = 200;
[Link]('Content-Type', 'text/plain');
[Link]('Hello, World!\n');
});
[Link](port, hostname, () => {
[Link](`Server running at [Link]
});
Line-by-Line Explanation
Line 1
const http = require('node:http');
Explanation:
const declares a constant variable.
require('node:http') imports the built-in HTTP module of [Link].
The HTTP module provides functions to create web servers and handle HTTP
requests and responses.
The imported module is stored in the variable http.
Purpose: Import the HTTP module.
Line 2
const hostname = '[Link]';
Explanation:
Declares a constant named hostname.
[Link] is the localhost IP address.
The server will run only on the local computer.
Purpose: Specify the IP address where the server will run.
Line 3
const port = 3000;
Explanation:
Declares the port number.
Port 3000 is commonly used for development.
Clients connect to the server using this port.
Purpose: Specify the communication port.
Line 4
const server = [Link]((req, res) => {
Explanation:
[Link]() creates a new HTTP server.
It accepts a callback function that executes whenever a client sends a request.
req (Request Object) contains information about the client's request.
res (Response Object) is used to send data back to the client.
Purpose: Create the web server and define how requests are handled.
Line 5
[Link] = 200;
Explanation:
Sets the HTTP status code.
200 means "OK".
It indicates that the request was processed successfully.
Common Status Codes:
Code Meaning
200 OK
404 Not Found
Code Meaning
500 Internal Server Error
403 Forbidden
Purpose: Inform the browser that the request was successful.
Line 6
[Link]('Content-Type', 'text/plain');
Explanation:
Sets the response header.
Content-Type tells the browser what kind of data is being returned.
text/plain means plain text.
Other examples:
text/html → HTML page
application/json → JSON data
image/png → PNG image
Purpose: Specify the type of response content.
Line 7
[Link]('Hello, World!\n');
Explanation:
Sends the response to the client.
"Hello, World!" is the message displayed in the browser.
\n adds a new line.
[Link]() also closes the response.
Purpose: Send the response and finish the request.
Line 8
});
Explanation:
Ends the callback function passed to createServer().
Line 9
[Link](port, hostname, () => {
Explanation:
Starts the server.
Listens on:
o IP Address: [Link]
o Port: 3000
The callback function runs once the server starts successfully.
Purpose: Make the server ready to receive client requests.
Line 10
[Link](`Server running at [Link]
Explanation:
Prints a message in the terminal.
Uses template literals (backticks `).
${hostname} inserts the hostname.
${port} inserts the port number.
Output:
Server running at [Link]
Purpose: Inform the developer that the server has started successfully.
Line 11
});
Explanation:
Ends the callback function for [Link]().
Workflow of JavaScript Code Executable by Creating a Web Server in [Link]
Start Program
│
▼
Import HTTP Module
(require('node:http'))
│
▼
Set Hostname ([Link])
│
▼
Set Port Number (3000)
│
▼
Create HTTP Server
([Link]())
│
▼
Client Sends Request
│
▼
Request Object (req) Created
│
▼
Process Request
│
▼
Set Status Code = 200
│
▼
Set Response Header
(Content-Type: text/plain)
│
▼
Send Response
"Hello, World!"
│
▼
Close Response
([Link]())
│
▼
Start Listening
([Link]())
│
▼
Open Browser
[Link]
│
▼
Browser Displays
Hello, World!
Expected Output
Terminal
Server running at [Link]
Browser ([Link]
Hello, World!
Viva (Exam) Questions with Answers
1. What is [Link]?
[Link] is a JavaScript runtime environment that executes JavaScript code outside the
browser and is commonly used to build server-side applications.
2. Why is the HTTP module used?
The HTTP module is a built-in [Link] module used to create web servers and handle HTTP
requests and responses.
3. What is req?
req is the request object that contains information sent by the client, such as the URL,
method, and headers.
4. What is res?
res is the response object used to send data, status codes, and headers back to the client.
5. What does statusCode = 200 mean?
It indicates that the server successfully processed the client's request.
6. What is the purpose of [Link]()?
It sends the response body to the client and closes the HTTP response.
7. What does [Link]() do?
It starts the server and listens for incoming client requests on the specified host and port.
b. Write a program Transfer Data over HTTP Protocol using the HTTP Module
([Link])
// Load the http module
const http = require('http');
// Define the port for the server
const PORT = 4000;
// Sample data to transfer
const data = {
id: 101,
name: "HTTP Data Transfer",
status: "Success",
description: "This data is sent over HTTP using [Link] http module"
};
// Create the server
const server = [Link]((req, res) => {
[Link](`Request received: ${[Link]} ${[Link]}`);
// Set response headers
[Link](200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
// Send the data as JSON
[Link]([Link](data));
});
// Start the server
[Link](PORT, () => {
[Link](`Server running at [Link]
});
Line-by-Line Explanation
Line 1
const http = require('http');
Explanation:
const declares a constant variable.
require('http') imports the built-in HTTP module of [Link].
The HTTP module allows [Link] applications to create web servers and transfer data
using the HTTP protocol.
Purpose: Import the HTTP module into the program.
Line 2
const PORT = 4000;
Explanation:
Declares a constant variable named PORT.
The server will listen for client requests on port number 4000.
Purpose: Specify the port where the server runs.
Line 3
const data = {
Explanation:
Creates a JavaScript object named data.
This object contains the information that will be transferred to the client.
Purpose: Store the response data.
Line 4
id: 101,
Explanation:
Adds an ID field with value 101.
Purpose: Represents the unique identifier.
Line 5
name: "HTTP Data Transfer",
Explanation:
Stores the name of the data.
Line 6
status: "Success",
Explanation:
Indicates that the request has been processed successfully.
Line 7
description: "This data is sent over HTTP using [Link] http module"
Explanation:
Stores a descriptive message explaining the response.
Line 8
};
Explanation:
Ends the JavaScript object definition.
Line 9
const server = [Link]((req, res) => {
Explanation:
[Link]() creates a new HTTP server.
The callback function executes whenever a client sends a request.
req (Request Object) contains details of the client's request.
res (Response Object) is used to send data back to the client.
Purpose: Create the web server and define request handling.
Line 10
[Link](`Request received: ${[Link]} ${[Link]}`);
Explanation:
Displays information about the incoming request in the terminal.
[Link] shows the HTTP method (GET, POST, etc.).
[Link] shows the requested URL.
Example Output
Request received: GET /
Purpose: Monitor incoming client requests.
Line 11
[Link](200, {
Explanation:
Sends the HTTP response status and headers.
200 means Request Successful (OK).
Purpose: Inform the client that the request was successful.
Line 12
'Content-Type': 'application/json',
Explanation:
Sets the response type to JSON.
The browser or client understands that JSON data is being returned.
Purpose: Specify the response format.
Line 13
'Access-Control-Allow-Origin': '*'
Explanation:
Allows requests from any website or domain.
* means all origins are permitted.
This is commonly used to avoid CORS (Cross-Origin Resource Sharing)
restrictions during development.
Purpose: Allow cross-origin access.
Line 14
});
Explanation:
Ends the response header configuration.
Line 15
[Link]([Link](data));
Explanation:
[Link](data) converts the JavaScript object into a JSON string.
[Link]() sends the JSON response to the client and closes the connection.
Example Response
{
"id":101,
"name":"HTTP Data Transfer",
"status":"Success",
"description":"This data is sent over HTTP using [Link] http module"
}
Purpose: Send JSON data and finish the response.
Line 16
});
Explanation:
Ends the callback function for createServer().
Line 17
[Link](PORT, () => {
Explanation:
Starts the server.
The server begins listening on port 4000.
The callback function runs once the server starts successfully.
Purpose: Activate the web server.
Line 18
[Link](`Server running at [Link]
Explanation:
Displays the server URL in the terminal.
Uses a template literal to insert the port number dynamically.
Output
Server running at [Link]
Purpose: Inform the developer that the server is running.
Line 19
});
Explanation:
Ends the callback function for [Link]().
Workflow of Data Transfer over HTTP
Start Program
│
▼
Import HTTP Module
│
▼
Define Port (4000)
│
▼
Create Sample Data Object
│
▼
Create HTTP Server
│
▼
Server Starts Listening
│
▼
Client Sends HTTP Request
│
▼
Request Received (req)
│
▼
Display Request in Console
│
▼
Set HTTP Status = 200
│
▼
Set Response Headers
(Content-Type: application/json)
│
▼
Convert Object to JSON
([Link]())
│
▼
Send JSON Response
([Link]())
│
▼
Client Receives Data
│
▼
End
Expected Output
Terminal
Server running at [Link]
Request received: GET /
Browser or API Client ([Link]
{
"id": 101,
"name": "HTTP Data Transfer",
"status": "Success",
"description": "This data is sent over HTTP using [Link] http module"
}
Viva Questions and Answers
1. What is the HTTP module in [Link]?
The HTTP module is a built-in [Link] module used to create web servers and transfer data
over the HTTP protocol.
2. What does [Link]() do?
It creates an HTTP server that listens for client requests and sends responses.
3. What are req and res?
req (Request Object): Contains information sent by the client, such as the HTTP
method, URL, and headers.
res (Response Object): Sends status codes, headers, and data back to the client.
4. Why is [Link](data) used?
It converts a JavaScript object into a JSON string because HTTP responses transmit text or
binary data, not raw JavaScript objects.
5. What does [Link](200, {...}) do?
It sends the HTTP status code (200 OK) and response headers before the response body.
6. What is the purpose of Content-Type: application/json?
It tells the client that the response body contains JSON data.
7. Why is Access-Control-Allow-Origin: * used?
It enables Cross-Origin Resource Sharing (CORS), allowing requests from any origin during
development.
8. What is the purpose of [Link]()?
It sends the response to the client and closes the HTTP connection.
c. Create a text file [Link] and add the following content to it. (HTML, CSS,
Javascript, Typescript, MongoDB, [Link], [Link], [Link])
Program: Create a Text File ([Link]) and Write Content Using the fs Module
// Load the fs (File System) module
const fs = require('fs');
// Define the file name and content
const fileName = '[Link]';
const content = `HTML
CSS
JavaScript
TypeScript
MongoDB
[Link]
[Link]
[Link]`;
// Write content to the file
[Link](fileName, content, (err) => {
if (err) {
[Link]('Error writing to file:', err);
return;
}
[Link](`${fileName} has been created with the given content.`);
});
Line-by-Line Explanation
Line 1
const fs = require('fs');
Explanation:
const declares a constant variable.
require('fs') imports the built-in File System (fs) module in [Link].
The fs module provides methods to create, read, write, update, and delete files.
Purpose: Import the File System module so the program can perform file operations.
Line 2
const fileName = '[Link]';
Explanation:
Declares a constant variable named fileName.
Stores the name of the file that will be created.
If [Link] does not exist, [Link] creates it.
If it already exists, its contents will be overwritten by default.
Purpose: Specify the file name.
Line 3
const content = `HTML
Explanation:
Declares a variable named content.
Uses backticks ( ) to create a template literal, allowing multiple lines of text without
using \n.
Purpose: Store the data that will be written into the file.
Lines 4–11
CSS
JavaScript
TypeScript
MongoDB
[Link]
[Link]
[Link]`;
Explanation:
These lines contain the text that will be written into [Link].
After execution, the file will contain:
HTML
CSS
JavaScript
TypeScript
MongoDB
[Link]
[Link]
[Link]
Purpose: Provide the file content.
Line 12
[Link](fileName, content, (err) => {
Explanation:
Calls the writeFile() method of the fs module.
fileName specifies where to write the data.
content is the text to write.
(err) => {} is a callback function that executes after the write operation completes.
writeFile() works asynchronously, so it does not block the execution of the rest of the
program.
Purpose: Write the specified content into the file.
Line 13
if (err) {
Explanation:
Checks whether an error occurred while writing the file.
If err contains a value, the write operation failed.
Purpose: Detect file-writing errors.
Line 14
[Link]('Error writing to file:', err);
Explanation:
Prints an error message to the terminal.
Displays the exact error returned by [Link].
Example Output
Error writing to file: [Error Details]
Purpose: Help identify and debug file-writing problems.
Line 15
return;
Explanation:
Stops the callback function immediately.
Prevents the success message from being displayed if an error occurs.
Purpose: Exit the callback when an error is detected.
Line 16
}
Explanation:
Ends the if block.
Line 17
[Link](`${fileName} has been created with the given content.`);
Explanation:
Displays a success message in the terminal.
Uses a template literal to insert the value of fileName.
If fileName = "[Link]", the output will be:
[Link] has been created with the given content.
Purpose: Inform the user that the file has been created successfully.
Line 18
});
Explanation:
Ends the callback function.
Ends the [Link]() method call.
Workflow of the Program
Start
│
▼
Import fs Module
│
▼
Define File Name ([Link])
│
▼
Store Content in Variable
│
▼
Call [Link]()
│
▼
Create File (if it doesn't exist)
or Overwrite Existing File
│
▼
Write Content into File
│
▼
Error?
┌──────────────┐
│ │
Yes No
│ │
▼ ▼
Display Display
Error Success Message
│ │
└──────┬───────┘
▼
End
Expected Output
Terminal
[Link] has been created with the given content.
[Link]
HTML
CSS
JavaScript
TypeScript
MongoDB
[Link]
[Link]
[Link]
Viva Questions and Answers
1. What is the fs module in [Link]?
The fs (File System) module is a built-in [Link] module used to create, read, write, update,
rename, and delete files and directories.
2. What does require('fs') do?
It imports the built-in File System module so that file operations can be performed.
3. What is [Link]()?
[Link]() is an asynchronous method that writes data to a file. If the file does not exist, it
creates it; if it exists, it replaces the existing content by default.
4. Why are backticks ( ) used for content?
Backticks create a template literal, making it easy to write multi-line text without adding \n
manually.
5. What is the purpose of the err parameter?
The err parameter contains error information if the file-writing operation fails. If there is no
error, its value is null.
6. What does [Link]() do?
It prints an error message to the console, helping identify problems during execution.
7. What is the difference between [Link]() and [Link]()?
[Link]() [Link]()
Displays normal output or success messages Displays error messages
Used for general information Used for debugging and error reporting
8. Is [Link]() synchronous or asynchronous?
[Link]() is asynchronous, meaning it writes the file without blocking the rest of the
program.