What is Node?

  1. Node is not a programming language rather runtime environment to run Javascript code
  2. Browsers provide runtime environment to run javascript.Node uses Chrome v8 engine internally to run js code.
  3. In Traditional server request are assigned a thread and the response would be server. So there exist one thread for each request.The threads cannot be shared and Blocking and Synchronous in nature
  4. In node there is single thread and all these request would be served by this single thread hence its is Nonblocking and Asynchronous in nature.
  5. Because of this asynchronous nature node is not suitable for Data intensive operations and for image manipulation, Since the threads would be locked for a long time
  6. Since node application runs in an environment outside broswer it provides file handling operations which are not possible by browsers.

How the Execution of js files in Node happens

  1. Node variables has 2 scopes –
    • Global Scope
    • Local Scope or Module Scope
  2. Variables like Window, Console is global scope as they are accessed globally over broswer
  3. In Node everything is a module. Each js file would be accounted for as a module. The js file execution happens within its own module scope.
  4. The below statements are same in node
      console.log('Uses console without global prefix');
      global.console.log('Uses console with global prefix');
     

    Output

    Uses console without global prefix
    Uses console with global prefix
    
  5. Let’s try to print the module variable in Node js using below code.The code below prints the details of the module such as js file name, exports done from module and so on.
      console.log(module); 
     

    Output

    Module {
      id: '.',
      exports: {},
      parent: null,
      filename: 'D:\\AngularProjects\\NodeServer\\index.js',
      loaded: false,
      children: [],
      paths:
       [ 'D:\\AngularProjects\\NodeServer\\node_modules',
         'D:\\AngularProjects\\node_modules',
         'D:\\node_modules' ] }
    
  6. Exporting Variable and Function From Module
    We exported a variable and a function from logger.js and we called the same in index.js.Now when you run console.log(module) we can see the exported functionality in exports
    logger.js

    var log = "Log Me"
    
    function getLoggedValue(message){
        console.log(message);
    }
    
    module.exports.log=log;
    module.exports.printLog=getLoggedValue;
     

    index.js

    const logger = require('./logger');
    console.log(logger.log);
    logger.printLog('Hi there');
    

    Output

    Log Me
    Hi there
    

    You can see what is imported simply by using below statement in index.js
    index.js

    const logger = require('./logger');
    console.log(logger);
    

    Output

    { log: 'Log Me', printLog: [Function: getLoggedValue] }
    
  7. In case you are having just a single function the same thing can be accessed in the imported js as below. Let export just a single function in logger.js
  8. logger.js

    var log = "Log Me"
    
    function getLoggedValue(message){
        console.log(message);
    }
    
    module.exports=getLoggedValue;
    

    index.js

    const logger = require('./logger');
    logger('Hi there');
    

    Output

    Hi there
    
  9. Node always executes modules inside immediately invokable function expression.It is called Module Wrapper Function
    (function(exports, require, module, __filename, __dirname) {
    // Module code actually lives in here
    });
    

    Before a module’s code is executed, Node.js will wrap it with a function wrapper that looks like the following:
    By doing this, Node.js achieves a few things:It keeps top-level variables (defined with var, const or let) scoped to the module rather than the global object.
    It helps to provide some global-looking variables that are actually specific to the module. The module and exports objects that the implementor can use to export values from the module.The convenience variables __filename and __dirname, containing the module’s absolute filename and directory path.

Modules in Node
Node is a combination of different modules we interact with based on our needs. Below are a few of them as listed.

  1. Path – Using path we are listing the details of the filename
  2. OS – We check for the total memory and free memory
  3. File – We list the files in the directory.Always use asynchrounous reading mode(fs.readdir) for file instead of (fs.readFileSync).
  4. Events
  5. Http

index.js

console.log('-------Path module-------');
const path = require('path');
var pathObj = path.parse(__filename);
console.log(pathObj);

console.log('------OS module--------');
const os = require('os');
var totalMem = os.totalmem();
var freeMem = os.freemem();
console.log(`Total Memory -  ${totalMem}`);
console.log(`Free Memory -  ${freeMem}`);

console.log('------FS Module--------');
const fs = require('fs');
fs.readdir('./', (err, files)=>{
    if(err)
     console.log('Error', err);
    else 
     console.log('Files', files);
});

Output

-------Path module-------
{ root: 'D:\\',
  dir: 'D:\\AngularProjects\\NodeServer',
  base: 'index.js',
  ext: '.js',
  name: 'index' }

------OS module--------
Total Memory -  8465264640
Free Memory -  1929568256

------FS Module--------
Files [ 'index.js', 'logger.js', 'package-lock.json', 'test.html' ]

Event Module
Event is a singnal which tells something has happened.Below is a simple code for event listener

  1. We acquire handle of event class using require in EventEmitter
  2. Create object using new for EventEmitter
  3. Add the event to listener and define a function which needs to be called when the event gets fired
  4. Adding the event could be done using addListener and also by using on method
  5. Emit the event using emit methid

index.js

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.addListener('Message Listener', ()=>console.log('Listener Called'));
emitter.emit('Message Listener');

Output

Listener Called

Lets try to pass arguments to event listener. Arguments should always be passed as JSON Objects as as one parameter inorder to avoid confusion though passing as a individual argument is going to work fine.
index.js

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.addListener('Message Listener', (argObj)=>{
                                                    console.log(argObj.argument1);
                                                    console.log(argObj.argument2);
                                                  });
emitter.emit('Message Listener', {'argument1':'arg1 val', 'argument2':'arg2 val'});

Output

arg1 val
arg2 val

Now let’s build a custom class which does the logging

  1. We have a logger.js which is a utility class with log method in it
  2. We call the log method from eventList class by importing the Logger Class
  3. In the logger we extend event emitter and use this reference to call the eventEmitter

logger.js

const EventEmitter = require('events');

class Logger extends EventEmitter
{
    log(strLogMessage)
    {
        this.emit('MessageListener', strLogMessage);        
    }
}

module.exports = Logger;

eventList.js

const Logger = require('./logger');

const objLogger = new Logger(); 

objLogger.addListener('MessageListener', (arg) =>{console.log(arg)});
objLogger.log('Calling the Log Method');

Output

Calling the Log Method

HTTP Module
server.js

const http = require('http');

const server = http.createServer();

const server = http.createServer((req, res)=>{
    if(req.url === '/')
    {
        res.write('Hello World...');
        res.end();
    }

    if(req.url === '/api/customers')
    {
        res.write(JSON.stringify(['Customer1', 'Customer2', 'Customer3']));
        res.end();
    }
});

server.listen(3000);
console.log('Listening on Port 3000.....');

Input and Output

IP : http://localhost:3000/
OP : Hello World...

IP : http://localhost:3000/api/customers
OP : ["Customer1","Customer2","Customer3"]
$start = Array(25000, 30000, 40000, 15900, 46000);
$end   = Array(45000, 47000, 60000, 55000, 85000);

$cnt2 = 0;

foreach($start as $val)
{
    $cnt  = 0;

    for($i=0;$i<count($start); $i++)
    {
        if($start[$i] <= $val && $val < $end[$i])           $cnt++;                  if($cnt == count($start))           $start_budget = $val;         elseif($cnt >$cnt2)
        {
     	  $cnt2			= $cnt;
     	  $start_budget = $val;
        } 
    }

    if($cnt2 == 0)
     $cnt2 = $cnt;

}

$cnt2 = 0;

foreach($end as $val)
{
    $cnt = 0;

    for($i=0;$i<count($end); $i++)
    {
      if($start[$i] < $val && $val <= $end[$i])        $cnt++;                if($cnt == count($end))        $end_budget = $val;       elseif($cnt > $cnt2)
      {
      	$cnt2 		= $cnt;
      	$end_budget = $val;
      }

      if($cnt2 == 0)
       $cnt2 = $cnt;      
    }   

}

echo $start_budget;
echo  "<br/>";
echo $end_budget;
Posted in PHP.

I have a Two PHP arrays as Below

Array 1 – Budget Start
$start = Array(25000,30000,35000,15900);

Array 2 – Budget End
$end = Array(40000,50000,60000,55000);

I want to Filter the Budget range which the user is actually looking for.For the above the budget range is 35000 For Budget Start and 40000 for Budget End.

Budget Start 35000 because
25000 <= 35000 < 40000
30000 <= 35000 < 50000
35000 <= 35000 < 60000
15900 <= 35000 < 55000

Budget End 40000 because
25000 < 40000 <= 40000
30000 < 40000 <= 50000
35000 < 40000 <= 60000
15900 < 40000 <= 55000

$start = Array(25000,30000,35000,15900);

$end = Array(40000,50000,60000,55000);

foreach($start as $val){
    $cnt = 0;
    for($i=0;$i<count($start); $i++){
        if($start[$i] <= $val && $val < $end[$i]){
            $cnt++;
        }
        if($cnt == count($start)){
            $start_budget = $val;
        }
    }
}

foreach($end as $val){
    $cnt = 0;
    for($i=0;$i<count($end); $i++){
        if($start[$i] < $val && $val <= $end[$i]){
            $cnt++;
        }
        if($cnt == count($end)){
            $end_budget = $val;
        }
    }
}

echo $start_budget;
echo "
";
echo $end_budget;
Posted in PHP.
package packA;

public class sam1 
{
 public static final double DIAMETER = 12756.32; // kilometers
 
 public static void hithere()
 {
	 System.out.println("Hi There");
 } 
}


package packB;
import packA.sam1;

public class sam2 
{
	public static void main(String args[])
	{
		sam2 objsam2 = new sam2();
		objsam2.halfway();		
	}
	
	public void halfway()
	{ 
		sam1.hithere();
		System.out.println(sam1.DIAMETER/2.0);
	}
}

-Two Packages – packA and packB – While importing static from packA to packB you should either use import packA.sam1; or import static packA.sam1.*;

Using import static packA.sam1; will not allow to access elements in package

If you use import packA.sam1;
className.StaticVariableName

If you use import static packA.sam1.*;
StaticVariableName

The below code generates no compilation error in eclipse but throws error during Runtime.

public class Animal
{
  public void eat(){}
}
public class Dog extends Animal
{
  public void eat(){}
  public void main(String[] args)
  {
    Animal animal=new Animal();
    Dog dog=(Dog) animal;
  }
}

Output

Exception in thread "main" java.lang.ClassCastException: com.mugil.wild.Animal cannot be cast to com.mugil.wild.Dog
	at com.mugil.wild.Dog.main(Dog.java:12)

By using a cast you’re essentially telling the compiler “trust me. I’m a professional, I know what I’m doing and I know that although you can’t guarantee it, I’m telling you that this animal variable is definitely going to be a dog

Because you’re essentially just stopping the compiler from complaining, every time you cast it’s important to check that you won’t cause a ClassCastException by using instanceof in an if statement.

Generally, downcasting is not a good idea. You should avoid it. If you use it, you better include a check:

Animal animal = new Dog();

if (animal instanceof Dog)
{
Dog dog = (Dog) animal;
}

public class ClassA 
{	
	public void MethodA()
	{
		System.out.println("This is Method A");
	}
}

public class ClassB extends ClassA
{	
	public void MethodB()
	{
		System.out.println("I am Method in Class B");
	}
}


public class ClassC 
{
	public static void main(String[] args) 
	{
		ClassA objClassA1 = new ClassA();
		ClassB objClassB2 = new ClassB();
		
		//Child Class of Parent Type can be Created  
		ClassA objClassB1 = new ClassB();
		
		//Assigning a Parent class Type to Child Class is Not Allowed  
		//Casting Should be Carried out
		ClassB objClassA2 = (ClassB) new ClassA();
		
		objClassA1.MethodA();
		objClassB2.MethodA();
		objClassB2.MethodB();
		
		objClassB1.MethodA();
	}
}

The following short quiz consists of 4 questions and will tell you whether you are qualified to be a professional. The questions are NOT that difficult.

1. How do you put a giraffe into a refrigerator?

Correct Answer: Open the refrigerator, put in the giraffe, and close the door. This question tests whether you tend to do simple things in an overly complicated way.

2. How do you put an elephant into a refrigerator?

Did you say, Open the refrigerator, put in the elephant, and close the refrigerator?

Wrong Answer.

Correct Answer: Open the refrigerator, take out the giraffe, put in the elephant and close the door. This tests your ability to think through the repercussions of your previous actions.

3. The Lion King is hosting an animal conference. All the animals attend…. except one. Which animal does not attend?

Correct Answer: The Elephant. The elephant is in the refrigerator. You just put him in there. This tests your memory.

Okay, even if you did not answer the first three questions correctly, you still have one more chance to show your true abilities.

4. There is a river you must cross but it is used by crocodiles, and you do not have a boat. How do you manage it?

Correct Answer: You jump into the river and swim across. Have you not been listening? All the crocodiles are attending the Animal Meeting. This tests whether you learn quickly from your mistakes.

In java String Builder Should be Used in case you need to perform concatenate more string together.

i.e

 public String toString()
 {
    return  a + b + c ;
 }

For the above code using + will be converted to

a = new StringBuilder()
    .append(a).append(b).append(c)
    .toString();

For the above case you can use concat as below but since + will be converted as String Builder its better to use + rather than concat.

 public String toString()
 {
    return  a.concat(b).concat(c);
 }

The key is whether you are writing a single concatenation all in one place or accumulating it over time.

There's no point in explicitly using StringBuilder.

But if you are building a string e.g. inside a loop, use StringBuilder.

To clarify, assuming that hugeArray contains thousands of strings, code like this:

...
String result = "";
for (String s : hugeArray) {
    result = result + s;
}

It should be as below

 ...
StringBuilder sb = new StringBuilder();

for (String s : hugeArray) {
    sb.append(s);
}
String result = sb.toString();