Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it

5 Feb 2024

NODE JS BUILT IN MODULE - HTTP


1) Creating an HTTP Server


1) We need to first import the 'http' module using the require function
                            var http = require ('http');

2) We will use the method createServer() to create an HTTP server:
                            http.createServer(function (req, res){
                            ... // your code here
                            }).listen(PORT_NUMBER); 

Example: 
// Import the built-in 'http' module 
const http = require('http'); 

// Define the hostname and port number 
const hostname = '127.0.0.1'; 
const port = 3000; 

// Create an HTTP server 
const server = http.createServer((req, res) => { 

        // Set the HTTP status code and content type in the response header 
        res.writeHead(200, {'Content-Type': 'text/plain'}); 

        // Send the response body 
        res.end('Hello, world!\n'); 

        }); 
        
// Start the server and listen on the specified port and hostname 
server.listen(port, hostname, () => { 
       console.log(`Server running at http://${hostname}:${port}/`); 
});


2) GET REQUEST to query



1) We will be using http.request() method to send an HTTP GET request to a server and handle the response.

2) Similarly, we will be importing the module using- 
                            var http = require ('http');

3) We will be defining the options for the HTTP request where we will be mentioning the hostname, port number, path (if any), and the method.
                            const options = {
                            hostname: 'jsonplaceholder.typicode.com',
                            port: 80,
                            path: '/posts',
                            method: 'GET'
                            }

4) Creating a http.request() method in which we are going to pass the above options object.

5) Store the response and display it or process it when the response is complete.

Example: 

// Import the built-in 'http' module 
const http = require('http'); 

// Define the options for the HTTP request 
const options = { 
        hostname: 'jsonplaceholder.typicode.com', 
        port: 80, 
        path: '/posts', 
        method: 'GET'
};

// Create the HTTP request 
const req = http.request(options, (res) => { 

        // Initialize a variable to store the response data 
        let data = ''; 

        // Concatenate chunks of data as they are received 
        res.on('data', (chunk) => { 
                data += chunk; 
        });
 
        // When the response is complete, log the data to the console 
        res.on('end', () => { 
            console.log(data); 
        }); 
}); 

// Handle errors that occur during the request 
req.on('error', (error) => { 
        console.error('An error occurred:', error); 
}); 

// End the request 
req.end(); 


MODULES IN NODE JS


 1) Modules in Node Js


1) In Node Js, modules are reusable blocks of code that encapsulate related functionality.

2) Modules allow you to organize your code into separate files and directories, making it easier to manage and maintain your projects.

3) We can define modules in separate files and then import and use them in other files using the 'require()' function (User-Defined Modules).

4) There are two types of modules - User-Defined Modules and Predefined Modules (Built-in Modules) 


1.1) What are User-Defined Modules?


Definition - User-defined modules are created by the developers to encapsulate and reuse the code across their own applications. These modules are typically stored in separate files within the applications's directory.

Developers can create their own modules and export them using the "module.exports".
The same modules can be imported and used in other parts of the application using the "require()" function.

Example: myFirstModule.js

function greetWithPersonName(name) {
        console.log ( `Hello ${name}! `);     
        //Here we have used the tilde operator
}

module.exports = greetWithPersonName;



1.2) What are Predefined Modules/ Built-in Modules/ Core Modules?


Definition: Predefined modules are provided by Node.js itself and are available for use without the need for installation. These modules are part of the Node.js runtime environment and provide various functionalities for common tasks such as file system operations, networking, HTTP, and more.

Developers can use the predefined modules by importing and using them in Node.js applications in the same way as user-defined modules, using the require() function.

Example: usePreDefMod.js

// We are going to use a file system module to manage the file 

const fs = require ('fs');

fs.readFile ('text.txt, 'utf8', (err, data) => {
        if (err) {
            console.error (err);
            return;
        }
        console.log (data);
});

NODE JS INTRODUCTION


1) What is Node Js?


- Node Js is an open-source server environment that runs on various platforms like Windows, Linux, Unix, Mac OS, etc.

- Node Js is a runtime environment that allows you to run JavaScript code on the server side.

- Node Js uses the V8 Javascript engine.

- Node Js is commonly used to build scalable network applications because of its event-driven, non-blocking I/O model, which makes it efficient and lightweight.



2) Why to use Node Js?

- Javascript can be used for Server-side and Client-side development (Frontend and Backend of an application).

- Node Js is an event-driven, non-blocking I/O model, which makes it efficient and scalable for handling concurrent connections. Node Js can handle multiple requests without getting blocked (Useful for real-time applications).

- V8 Javascript engine compiles JavaScript directly into machine code before executing it (High Performance).

- Since Node Js is non-blocking, and has event-driven architecture, it is inherently scalable (Can easily handle many concurrent connections).

- Plenty of resources and support available for developers who are using Node Js (Documentation, Tutorial, and more)


3) How to download Node Js?



- Node js can easily be installed from the official site - https://nodejs.org/en


4) Writing the first Node Js program.



// Import the built-in 'http' module
const http = require('http');

// Create an HTTP server that listens on port 5000
const server = http.createServer((req, res) => {
     // Set the response HTTP header with HTTP status and content type
     res.writeHead(200, {'Content-Type': 'text/plain'});

    // Write the response body ("Hello, world!")
    res.end('Hello World!!');
});

// Start the server and listen on port 5000
server.listen(5000, () => {
    console.log('Server is now running at http://localhost:5000/');
});

To run this code on your local machine:-
1) Copy and paste the above code into the file - helloworld.js
2) Open the command prompt and navigate to the folder where helloworld.js is saved
3) Run the command node helloworld.js
4) You should see the message "Server is now running at http://localhost:5000/"
5) Open any web browser and navigate to http://localhost:5000/ and you will see Hello World!!

Click Here to Learn Modules in Node Js

21 Jan 2024

C program that uses a loop to calculate the factorial of a given number

// Factorial program using function


#include <stdio.h>

// Function prototype

long long calculateFactorial(int n);

int main() {

    int number;
    // Get input from the user

    printf("Enter a non-negative integer: ");
    scanf("%d", &number);

    // Check if the input is non-negative

    if (number < 0) {
        printf("Please enter a non-negative integer.\n");
        return 1; // Return with an error code
   }

    // Calculate and display the factorial using a loop

    long long factorial = calculateFactorial(number);
    printf("Factorial of %d = %lld\n", number, factorial);
    return 0;

}

// Function to calculate factorial using a loop

long long calculateFactorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
         long long result = 1;
        for (int i = 2; i <= n; ++i) {
           result *= i;
        }
        return result;
    }
}


14 Jan 2024

C program example that uses functions - This program calculates the sum of two numbers using separate functions for input, addition, and output.


#include <stdio.h>

// Function prototypes
    int getInput();
    int addNumbers(int num1, int num2);
    void displayResult(int result);

int main() {
    // Get input from the user
    int number1 = getInput();
    int number2 = getInput();

    // Perform addition
    int sum = addNumbers(number1, number2);

    // Display the result
    displayResult(sum);
    return 0;
}


// Function to get input from the user
    int getInput() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    return num;
}

// Function to add two numbers
    int addNumbers(int num1, int num2) {
    return num1 + num2;
}

// Function to display the result
    void displayResult(int result) {
    printf("The sum is: %d\n", result);
}


1 Jan 2024

Node js program - IF ELSE IF example

# Node js program using if else if statement

var a = 'route 1';

if (a === 'route 1'){
    console.log ('Route is 1');
}else if ( a === 'route 2')  {
     console.log ('Route is 2');
}else {
    console.log ( 'No Route');
}


## When you run this program
## Output will be - 
Route is 1

Node js program - IF ELSE example

# Node js program using if else statement

var a = 'route 1';

if (a === 'route 1'){
    console.log ('True');
}else {
     console.log ('False');
}


## When you run this program
## Output will be - 
True

30 Dec 2023

What is an Algorithm?

An algroithm definition is as simple as a set of step-by-step procedures or a list of rules to follow for completing a specific task or solving a particular problem.

Example of an algorithm for baking a cake ->

1) Gather all the ingredients
2) Pre-heat the oven
3) Measure out the ingredients
4) Mix together to make the batter
5) Put the butter into the pan
6) Pour the batter into the pan
7) Put the pan in the oven
8) Set a timer
9) When the timer goes off, take the pan out of the over
10) Eat the cat and ENJOY!

29 Dec 2023

Algorithm to Multiply two numbers

function multiplyTwoNumbers(a, b):
result = 0 // Initialize the result to zero

// Iterate through each digit of the second number (y)
while y > 0:
// If the rightmost digit of y is 1, add the current value of x to the result
if y is odd:
result = result + x

// Shift both x and y to the right
x = x << 1

// Multiply x by 2 (left shift)
y = y >> 1

// Divide y by 2 (right shift)
return result