Thursday, 21 November 2024

PHP Advanced-2

 Example-1


<?php

 echo "<h3>Date/Time functions</h3><br>";

 echo date("d/m/y")."<br/>";

 echo date("d M,Y")."<br/>";

 $date_array = getdate(); 

 foreach ( $date_array as $key => $val )

 {  

  print "$key = $val<br />"; 

 }

 echo var_dump(checkdate(2,29,2003))."<br>";

 echo var_dump(checkdate(2,29,2004))."<br>";

 echo time();

 echo(date("M-d-Y",mktime(0,0,0,12,36,2001))."<br>");

 echo(date("M-d-Y",mktime(0,0,0,1,1,99))."<br>");

 $formated_date = "Today's date: "; 

 $formated_date .= $date_array['mday'] . "/"; 

 $formated_date .= 

 $date_array['mon'] . "/";

 $formated_date .= $date_array['year']; 

 print $formated_date; 

 print date("m/d/y G.i:s<br>", time()); 

 print "Today is ";

 print date("j of F Y, \a\\t g.i a", time()); 

 echo "<br><h3>Math functions</h3>";

 echo abs(6.7)."<br>";

 echo abs(-6.7)."<br>";

 echo abs(-3)."<br>";

 echo abs(3);

 echo ceil(0.60)."<br>";

 echo ceil(0.40)."<br>";

 echo ceil(5)."<br>";

 echo ceil(5.1)."<br>";

 echo ceil(-5.1)."<br>";

 echo ceil(-5.9);

 echo exp(0)."<br>";

 echo exp(1)."<br>";

 echo exp(10)."<br>";

 echo exp(4.8);

 echo floor(0.60)."<br>";

 echo floor(0.40)."<br>";

 echo floor(5)."<br>";

 echo floor(5.1)."<br>";

 echo floor(-5.1)."<br>";

 echo floor(-5.9)."<br>";

 echo rand(10,100)."<br>";

 echo min(2,4,6,8,10)."<br>";

 echo max(2,4,6,8,10)."<br>";

 echo pow(2,4)."<br>";

 echo round(0.60)."<br>";

?>

 Example-2


<?php

         $string1="Hello Friend ";

         $string2="Welcome";

         echo "<br>";

        echo $string1 . " " . $string2;

        echo "<br>";

        echo strlen($string1);

        echo "<br>";

        echo strpos("Hello world!","world"); 

        echo "<br>";

         echo strtoupper($string1);

        echo "<br>";

        echo substr_replace($string1, "T",6,1);

        echo "<br>";

        echo substr($string1,0,5);

        echo "<br>";

        echo substr_count($string1,"e");

?> 


 Example-3

<?php     
$to_email = 'vainshbharatit@gmail.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'vainsh_bharat@yahoo.com;
mail($to_email,$subject,$message,$headers);
?>


 Example-4

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

 Example-5

<?php
// Start the session
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>


 Example-6

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>


Example-7

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>

PHP Advanced-1

 Example-1

<?php

echo"First 10 Fibonacci no.";

$i=1;

$j=1;

echo"$i , $j ,";

for($k=2;$k<50;$k++)

{

$k=$i+$j;

$i=$j;

$j=$k;

echo" $k ,";

}

?>


 Example-2

<!DOCTYPE html>

<html>

<body>


<form name="f1" action="upload.php" method="post" enctype="multipart/form-data">

  Select image to upload:

  <input type="file" name="fileToUpload" id="fileToUpload">

  <input type="submit" value="Upload Image" name="submit">

</form>


</body>

</html>


 Example-3


<?php

$target_dir = "uploads/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$uploadOk = 1;

$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));


// Check if image file is a actual image or fake image

if(isset($_POST["submit"])) {

  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);

  if($check !== false) {

    echo "File is an image - " . $check["mime"] . ".";

    $uploadOk = 1;

  } else {

    echo "File is not an image.";

    $uploadOk = 0;

  }

}


// Check if file already exists

if (file_exists($target_file)) {

  echo "Sorry, file already exists.";

  $uploadOk = 0;

}


// Check file size

if ($_FILES["fileToUpload"]["size"] > 500000) {

  echo "Sorry, your file is too large.";

  $uploadOk = 0;

}


// Allow certain file formats

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"

&& $imageFileType != "gif" ) {

  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";

  $uploadOk = 0;

}


// Check if $uploadOk is set to 0 by an error

if ($uploadOk == 0) {

  echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file

} else {

  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

  } else {

    echo "Sorry, there was an error uploading your file.";

  }

}

?>


Example-4

<?php
function calcAverage()
{
    // initialize value to be used in calculation
    $total = 0;

    // find out how many arguments were given
    $arguments = func_num_args();     

    // loop to process each argument separately
    for ($i = 0; $i < $arguments; $i++) {
        // add the value in the current argument to the total
        $total += func_get_arg($i);
    }

    // after adding all arguments, calculate the average
    $average = $total / $arguments;

    // return the average
    return $average;
}

// invoke the function with 5 arguments

echo calcAverage(44, 55, 66, 77, 88);

// invoke the function with 8 arguments
echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7);



Example-5

<html>

<body>

<?php

if(isset($_POST["submit"]))

{

$value = $_POST['val1'];

}

else

{

$value = "";

}

?>


<form name="f1" action="#" method="post">


Enter Age<input type="text" name="val1" required/>


<input type="submit" name="submit">

</form>



<?php

if($value)

{

if($value>=18)

    echo "You are Eligible for Vote"; }

else

    echo "You are not Eligible for Vote"; }

}

?>

</body>

</html>


Example-6

<html>
<body>

<form name="f1" action="verify.php" method="post">
<select name="book">
    <option></option>
    <option>ADA</option>
    <option>WT</option>
</select>

Quantity
<input type="text" name="q1">
<input type="submit">
</form>

</body>
</html>


Example-7

<html>
<body>
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("h:m:s")."<br>";
?>
<?php require();>
</body>
</html>


PHP Basic-2

 Example-1


<!DOCTYPE html>

<html>

  <head>

    <title></title>

  </head>

  <body bgcolor="white">

  <?php

if(isset($_POST['submit']))

{

        $num=$_POST['num1'];

        define('NUM',$num);


        for($i=1;$i<=10;$i++)

        {

            echo $i*NUM;

            echo '</br>';

        }

}

  ?>

<form name="f1" method="post" action="#">

Enter Number<input type="text" name="num1" size="25" required>

<input type="submit" name="submit"/>

</form>

</body>

</html>


 Example-2

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body bgcolor="white">

  <?php

$x=8;
if($x>5)
{
    echo "$x is greater than 5</br>";
}
if($x<10)
{
    echo "$x is also less than 10</br>";

}

  ?>

 Example-3

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body bgcolor="white">
  <?php
      $a=80;
      echo "your grade is:";
      switch($a)
      {
          case $a>=90:
            echo "A</br>";
          break;

          case $a>=80:
            echo "B</br>";
          break;

          case $a>=70:
            echo "C</br>";
          break;

          default
          echo "you have fail";
         break;
      }
  ?>
</body>
</html>


 Example-4

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body bgcolor="white">

  <?php

      $a=10;

      while($a>=0)
      {
          echo"no is".$a."\n";
          $a--;

      }
     

  ?>

  <?php
          echo "hello world".$a;
          print ""

  ?>


 Example-5

<?php
          if(isset($_POST['submit']))
          {
            
           $num1=$_POST['val1'];

           if($num1%2==0)
              {
                  echo "Even No.";
              }
              else
              {
                  echo "Odd No.";
              }  
            }
          
   ?>

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body bgcolor="white">

  <form name="f1" action="#" method="post">

Enter No.<input type="text" name="val1" size="20">

<input type="submit" name="submit" value="check">
        </form>


   </body>
   </html>
   

 Example-6

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>

  <body bgcolor="white">

  <?php
$a=0;
$b=0;

for($i=0;$i<=5;$i++)
{
    $a+=10;
    $b+=5;
}

echo"at end of the loop a= $a and b=$b</br>";
 


$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  echo "$value </br>";
}


function myname($name)
{
    echo "your name is".$name."</br>";    

}

echo "Hi!";
myname("james");


function mul($x,$y)
{
    $total=$x*$y;
    return $total;

}

echo "the value of=".mul(7,3);
echo "</br>";
function add_five(&$value) {
    $value += 5;
  }
  
  $num = 2;
  add_five($num);
  echo $num;
  
  echo "</br>";

  function hello()
  {

    echo "hi";

  }

  $check="hello";

  $check();

  $sub=array("wd","ADA");
  echo $sub[0]."and" .$sub[1]."are good subjects";


  $char=array(name=>"suresh",age=>22);
    echo $char[age];

    $char1=array(
          array(firstname=>"ravi",lastname=>"patel"),
          array(firstname=>"mayur",lastname=>"xyz")
        );

        //echo $char1[firstname];

        foreach($char1 as $val)
        {
            foreach($val as $key=>$final_val)
            {
                echo "$key:$final_val</br>";

            }
        }

        $cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
echo"</br>";

$check=array("free","program","apple");
sort($check);
echo $check;
//print($check);

foreach($check as $var)
{
    echo "$var</br>";

}

//array_slice()

$first=array("a","b","c","d","e");
$second=array_slice($first,1,2);
foreach($second as $var)
{
    echo "$var</br>";

}

//array_merge()

$first=array("a","b","c","d","e");
$second=array(1,2,3);
$third=array_merge($first,$second);
foreach($third as $var)
{
    echo "$var";

}

?>
</body>
</html>


 Example-6

<html>
<body>
<?php
if(isset($_POST["submit"]))
{
$value = $_POST['val_1'];
}
else
{
$value = "";
}
?>
<form method="POST" action="">
Enter your age <br>
<input type="text" name="val_1" value="<?php echo $value; ?>"> <br />
<input type="submit" name="submit" value= "click here">
</form>
<?php
if($value)
{
if($value>=18)
{ echo "You are Eligible for Vote"; }
else
{ echo "You are not Eligible for Vote"; }
}
?>
</body>
</html>


 Example-7

<html>
<head>
<title>STAR</title>
</head>
<body>
<h2>PYRAMIND</h2>
<?php
if(isset($_POST[“Submit”]))
{
$val = $_POST[“val”];
$symbol = $_POST[“symbol”];
}
else if(isset($_POST[“clear”]))
{
$val = “”;
$symbol = “”;
}
else
{
$val = “”;
$symbol = “”;
}?>
<form method=”POST”>
Enter the loop Number <input type=”text” name=”val” value="<?php echo”$val”; ?>" />
</br>
Enter the Symbol <input type=”text” name=”symbol” value="<?php echo”$symbol”; ?>"/>
</br>
<input type=”submit” name=”Submit”>
<input type=”submit” name=”clear” value=”Reset” >

</form>
<?php
if($val and $symbol)
{
if(is_numeric($val))
{ for($i=1;$i<=$val;$i++)
{
for($j=1;$j<=$i;$j++)
{
echo “&nbsp “.$symbol;
}
echo “<br />”;
}
}

else
{
echo “Enter loop in Digits”;
}
}
?>
</body>
</html>


PHP Basic-1

 Example 1: 

 <!DOCTYPE html>

<html>

  <head>

    <title></title>

  </head>

  <body bgcolor="white">


  <?php

        echo "hello world</br>";

        print "hi!how are you?";

          ?>

</body>

</html>



 Example 2:

<html>

<head>

<script type="text/javascript">

$(document).ready(function(e){

 $('#btnSubmit').click(function(){ 

 var email = $('#txtEmail').val();

 if ($.trim(email).length == 0) {

 alert('Please Enter Valid Email Address');

 return false;

 }

 if (validateEmail(email)) {

 alert('Valid Email Address');

 return false;

 }

 else {

 alert('Invalid Email Address');

 return false;

 }});

});

</script>

</head> <body>

Email Address: <input type="text" id="txtEmail"/><br/>

<input type="submit" id="btnSubmit" Value="Submit" />

</body>

</html> 


 Example 3:

<html>

<body>

<form name="myform" action="welcome.php" method="post">

Name: <input type="text" name="name"><br>

E-mail: <input type="text" name="email"><br>

<input type="submit" name="submit">

</form>

</body>

</html>


 Example 4:

<?php

if(isset($_POST['submit']))

{

$num1=$_POST['num1'];

$num2=$_POST['num2'];


$result=$num1+$num2;


echo "Sum of " .$num1. " and ".$num2. " is " .$result;

}

?>

<!DOCTYPE html>

<html>

<head>

<title>Add two number</title>

</head>

<body>

<table>

<form name="add" action="#" method="post">

<tr>

<td>Number 1 :</td>

<td><input type="text" name="num1" required></td>

</tr>

<tr>

<td>Number 2 :</td>

<td><input type="text" name="num2" required></td>

</tr>

<tr>

<td></td>

<td><input type="submit" value="Add" name="submit" /></td>

</tr>

</form>

</table>

</body>

</html>


  Example 5:

<!DOCTYPE html>

<html>

  <head>

    <title></title>

  </head>

  <body bgcolor="white">

  <?php

        echo "hello world</br>";

        print "hi!how are you?";

        $text1="hello";

        $text2=10;

        echo $text1;

        echo $text2;

        echo $text1 ." " .$text2;

        echo $text1;

        print($text1);

        $bikes=array("yamaha","royal","honda","hero");

        var_dump($bikes);

        echo  "array element 1:$bikes[0] $bikes[1]$bikes[2] </br>";

        $x = "Hello world!";

        $x = null;

        var_dump($x);

echo "</br>";

      $x = 5985;

var_dump($x);

$cars = array("Volvo","BMW","Toyota");

var_dump($cars);

echo "</br>";

$text="hello world";

$text=null;

echo $text;

var_dump($text);

echo "</br>";

        $text2="xyz\"this is string\"pqr";

        echo $text2;

        echo "</br>";

        echo strlen("php programming");

        echo "</br>";

        echo str_word_count("php programming language"); 

        echo "</br>";

        echo strrev("JAMES"); 

        echo strpos("Hello world!", "world"); 

        echo strpos("developer news","news");

       $x = 5985;

        var_dump(is_int($x));

        $x = 1.9e411;

        var_dump($x);

        $x = acos(8);

        var_dump($x);

        echo "</br>";

// Cast float to int

$x = 23465.768;

$int_cast = (int)$x;

echo $int_cast;

echo "<br>";

// Cast string to int

$x = "23465.768";

$int_cast = (int)$x;

echo $int_cast;

echo "<br>";

echo(pi()); // returns 3.1415926535898

echo "<br>";

echo "<br>";

echo(rand(1000, 10000));

define("cars", [

  "Alfa Romeo",

  "BMW",

  "Toyota"

]);

echo cars[0];

    ?>

</body>

</html>


  Example 6:

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body bgcolor="white">

  <?php

    $a=45;
    $b=35;

    $temp=$a;
    $a=$b;
    $b=$temp;

    echo "after the swapping :</br></br>";
    echo "a=".$a. "b=".$b;

  ?>

  Example 7:

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body bgcolor="white">

  <?php


    $a=45;
    $b=35;
    $c=20;

     
    if($a>$b and $a>$c)
    {
        echo "Max No. is $a";
    }
    elseif($b>$c)
    {
        echo "Max No. is $b";

    }
    else
    {
      echo "Max No. is $c";

    }

   ?>
   </body>
   </html>
   

Friday, 3 March 2023

Node JS Details

 Example 1:

var events = require('events');

var eventEmitter = new events.EventEmitter();

var connectHandler = function connected() {

   console.log('connection succesful.');

   eventEmitter.emit('data_received');

}

eventEmitter.on('connection', connectHandler);

eventEmitter.on('data_received', function() {

   console.log('data received succesfully.');

});

eventEmitter.emit('connection');

console.log("Program Ended.");


 Example 2:

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {

   if (err) return console.error(err);

   console.log(data.toString());

});

console.log("Program Ended");

 Example 3:

var fs = require("fs");

var data = fs.readFileSync('input.txt');

console.log(data.toString());

console.log("Program Ended");

 Example 4:

function a_function(fn) {

    console.log('before');

    // call the call back function.  It requires 2 arguments.

    var result = fn(4, 5);

    console.log('after');

    return result;

  }

  function test() {

    var result = a_function(function(x, y) {

      var value = x + y;

      console.log(value);

      return value;

    });

    console.log('result: ' + result);

  }

  test()

 Example 5:

function test(container) 

{

    var idx = 0;

    while (idx < container.length)

     {

      console.log('item: ' + container[idx]);

      idx += 1;

    }

  }

  var container = [11, 22, 33, ];

  test(container);

 Example 6:


// Node program to demonstrate theurl object properties 

 

// Get different parts of the URL

// using object properties

const url = require('url');

 

// URL address

const address ='https://smarteportal.blogspot.com';

 

// Call parse() method using url module

let urlObject = url.parse(address, true);

console.log('Url host');

 // Returns 'smarteportal.blogspot.com'

console.log(urlObject.host);

console.log('Url pathname');

 console.log(urlObject.pathname);

console.log('Url search');

console.log(urlObject.search);

let queryData = urlObject.query;

console.log(queryData);

console.log('Url query object');

console.log(queryData.lang);


 Example 7:


const http = require('http')


const hostname = '127.0.0.1'

const port = 8000


const server = http.createServer((req, res) =>

{

res.statusCode = 200

res.setHeader('Content-Type', 'text/plain')

res.end('Hello World\n')

})

server.listen(port, hostname, () =>

{

console.log(`Server running at http://${hostname}:${port}/`)

})


 Example 8:

var Calc = function() {

    'use strict';


    this.vars = {

        pi: Math.PI

    };

};


Calc.prototype.evaluate = function(expression) {

    'use strict';


    // Trigger final instruction to execute at end.

    expression += ' ';


    // Loop Variables


    var length = expression.length,

        iter,

        char,

        type;


    // Flags


    var flag_number = false,

        flag_float = false,

        flag_keyword = false,

        flag_operator = false,

        flag_operator_waiting = false,

        flag_brackets = 0,

        flag_var = false,

        flag_var_name = '',

        flag_math = false,

        flag_math_op = '';


    // Parser Variables


    var buffer = '',

        total = 0,

        cur_operator = null,

        buffer_parsed = 0;


    // Math Functions


    var stdOps = ['log', 'tan'],

        customOps = {

            fact: function(value) {

                var iter,

                    multiplier;


                for(multiplier = value - 1; multiplier > 0; --multiplier) {

                    value *= multiplier;

                }


                return value;

            },


            sin: function(value) {

                return Math.sin(value * Math.PI / 180);

            },


            cos: function(value) {

                return Math.cos(value * Math.PI / 180);

            }

        };



    // Helper Functions


    function isAlpha(char) {

        return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(char) !== -1;

    }


    function isNumeric(char) {

        return '1234567890.,'.indexOf(char) !== -1;

    }


    function isSpecial(char) {

        return '+-*/^'.indexOf(char) !== -1;

    }


    function applyOperator(left, right, operator) {

        // Addition

        if(operator === '+') {

            return left + right;

        }


        // Subtraction

        if(operator === '-') {

            return left - right;

        }


        // Division

        if(operator === '/') {

            return left / right;

        }


        // Multiplication

        if(operator === '*') {

            return left * right;

        }


        if(operator === '^') {

            return Math.pow(left, right);

        }


        return null;

    }


    for(iter = 0; iter < length; ++iter) {

        char = expression.charAt(iter);


        // Are we parsing a number

        if(flag_number) {

            // The number has finished

            if(!isNumeric(char)) {

                if(isSpecial(buffer) && !isSpecial(char)) {

                    flag_number = false;

                    flag_operator = false;

                }


                // Is it a float?

                if(flag_float) {

                    buffer_parsed = parseFloat(buffer, 10);

                } else {

                    buffer_parsed = parseInt(buffer, 10);

                }


                // Is there an operator waiting?

                if(cur_operator !== '' && cur_operator !== null) {

                    total = applyOperator(total, buffer_parsed, cur_operator);


                    // Reset flags

                    flag_number = false;

                    flag_float = false;

                    flag_operator_waiting = false;


                    // Unkown operator

                    if(total === null) {

                        process.stdout.write('Unrecognised operator ' + cur_operator);

                        break;

                    }


                    // Reset current operator

                    cur_operator = '';

                } else {

                    // Is a mathematical function waiting? (sin, cos, tan etc)

                    if(flag_math) {

                        flag_math = false;

                        buffer = flag_math_op(buffer_parsed).toString();


                        // Check if float

                        if(buffer.indexOf('.') !== -1) {

                            flag_float = true;

                        }


                        iter--;

                        continue;

                    }


                    // Else it's just a number, function call, or variable at the beginning of the expression

                    total = buffer_parsed;

                    flag_number = false;

                }


                buffer = '';

                cur_operator = '';

            } else {

                // Check for float

                if(char === '.') {

                    flag_float = true;

                }


                // Allow for commas

                if(char === ',') {

                    continue;

                }


                buffer += char;

                continue;

            }

        }


        if(flag_keyword) {

            if(!isAlpha(char)) {

                flag_keyword = false;


                // Case insensitivity

                buffer = buffer.toLocaleLowerCase(buffer);


                switch(buffer) {

                    case 'exit':

                        process.exit();


                        break;


                    case 'set':

                        // setting a variable

                        flag_var = true;


                    default:

                        // Standard Math.[sin|cos|tan|log] operations

                        if(stdOps.indexOf(buffer) !== -1) {

                            flag_math = true;

                            flag_math_op = Math[buffer];

                        }


                        // Custom operations: fact (factorial)

                        if(buffer in customOps) {

                            flag_math = true;

                            flag_math_op = customOps[buffer];

                        }


                        // If not mathematical function, it must be a variable

                        if(!flag_math) {

                            // Are we setting a variable?

                            if(flag_var) {

                                flag_var_name = buffer;

                            } else {

                                // We are referencing a variable, not setting it

                                if(buffer in this.vars) {

                                    buffer = this.vars[buffer].toString();

                                    flag_number = true;

                                    // Check if variable is float

                                    if(buffer.indexOf('.') !== -1) {

                                        flag_float = true;

                                    }

                                    --iter;

                                    continue;

                                }

                            }

                        }

                }


                buffer = '';

            } else {

                buffer += char;

                continue;

            }

        }


        // Are we parsing an operator?

        if(flag_operator) {

            // Are we ending an operator?

            if(!isSpecial(char) || char === '-' || char === '+') {

                // reset flags

                flag_operator = false;

                cur_operator = buffer;

                // reset buffer

                buffer = '';

                flag_operator_waiting = true;


                if(char === '-' || char === '+') {

                    flag_number = true;

                    buffer += char;

                    continue;

                }

            } else {

                buffer += char;

                continue;

            }

        }


        // A number has started

        if(isNumeric(char)) {

            flag_number = true;

            buffer += char;

            continue;

        }


        // A keyword, variable or function has started

        if(isAlpha(char)) {

            flag_keyword = true;

            buffer += char;

            continue;

        }


        // An operator has started

        if(isSpecial(char)) {

            if((char === '-' || char === '+') && (flag_operator_waiting || flag_math)) {

                buffer += char;

                flag_number = true;

                continue;

            } else {

                flag_operator = true;

                buffer += char;

                continue;

            }

        }


        // Parse parentheses

        if(char === '(') {

            var bIndex = expression.indexOf(')', iter + 1);


            if(bIndex !== -1) {

                // extract and independtly evaluate this sub-expression, in a recursive fashion

                buffer = this.evaluate(expression.substring(iter + 1, bIndex)).toString();

                flag_number = true;

                flag_float = buffer.indexOf('.') !== -1;

                iter = bIndex;


                continue;

            } else {

                console.log("Invalid bracket syntax");

                break;

            }

        }

    }

    // We are setting a variable

    if(flag_var) {

        this.vars[flag_var_name] = total;

    }

    return total;

};

var calc = new Calc();

process.stdin.resume();

process.stdin.setEncoding('utf8');

process.stdin.on('data', function(expression) {

    console.log(calc.evaluate(expression))

    process.stdout.write("> ");

});

console.log("Welcome to calc.js:");

process.stdout.write("> ");


 Example 9:


let os=require('os');

let totalmemory=os.totalmem();

let freememory=os.freemem();

console.log('total memory:' +totalmemory);

console.log('free memory:' +freememory);

console.log('Total Memory: ${totalMemory}')

console.log('Free Memory: ${freeMemory}')


 Example 10:


// Throws with a ReferenceError because b is undefined  

try

{  

    const a = 1; 

    const b = 1;

    const c = a + b;  

    console.log(c); 

}

catch (err)

{  

    console.log(err);  


Thursday, 19 January 2023

Node JS in details

Node JS in details Example

Events and Event Loop,Work with File System,

Example:1

var fs = require("fs");


fs.readFile('input.txt', function (err, data) {

   if (err) return console.error(err);

   console.log(data.toString());

});


console.log("Program Ended");


Example:2


var fs = require("fs");

var data = fs.readFileSync('input.txt');


console.log(data.toString());

console.log("Program Ended");


Example:3


function sayHello(name) 

{

    console.log( "Hello" +name);

 }

 

 // Now call above function after 2 seconds

 sayHello('james');


Example:4


var globalvar1 = 25;

var z = 20;


function test(x, y)

{

  var z = 10;

  console.log('x: ' + x);

  console.log('y: ' + y);

  console.log('z: ' + z);

  console.log('globalvar1: ' + globalvar1);

}


test(11, 22);


Example:5


    var number=7;

    if(number%2==0)

    {

    console.log("Even Number");

    }

    else

    {

    console.log("odd number");

    }


Example:6


function a_function(fn) {

    console.log('before');

    // call the call back function.  It requires 2 arguments.

    var result = fn(4, 5);

    console.log('after');

    return result;

  }

  

  function test() {

    var result = a_function(function(x, y) {

      var value = x + y;

      console.log(value);

      return value;

    });

    console.log('result: ' + result);

  }

  

  test();


Example:7

function test(container) 

{

    var idx = 0;

    while (idx < container.length)

     {

      console.log('item: ' + container[idx]);

      idx += 1;

    }

    

  }

  

  var container = [11, 22, 33, ];

  test(container);


Example:8


// Get different parts of the URL

// using object properties

const url = require('url');

 

// URL address

const address ='https://smarteportal.blogspot.com';

 

// Call parse() method using url module

let urlObject = url.parse(address, true);

 

console.log('Url host');

 

// Returns 'smarteportal.blogspot.com'

console.log(urlObject.host);

console.log('Url pathname');

 

// Returns '/projects'

console.log(urlObject.pathname);

console.log('Url search');

 

// Returns '?sort=newest&lang=nodejs'

console.log(urlObject.search);

  

// Get query data as an object

// Returns an object:

// { sort: 'newest', lang: 'nodejs' }

let queryData = urlObject.query;

console.log(queryData);

console.log('Url query object');

 

// Returns 'nodejs'

console.log(queryData.lang);


Example:9

const http = require('http')


const hostname = '127.0.0.1'

const port = 8000


const server = http.createServer((req, res) =>

{

res.statusCode = 200

res.setHeader('Content-Type', 'text/plain')

res.end('Hello World\n')

})

server.listen(port, hostname, () =>

{

console.log(`Server running at http://${hostname}:${port}/`)

})