Tuesday, June 30, 2015

Modules in node js (Scope and design patterns)

Scope in nodejs: 
Setting proper scope of the variable is important in JavaScript and same is applicable to node. We should avoid using global variable in node js since there may be collision in variables.

When we import a module, it caches the module, which is good thing. But, sometimes it may cause problem.

For example: In following module if we set "values" as a global variable, then last object value to global variable will be set and it will override the previous object values.


Solution: 

  1. Declare private variable in module that you do not want to expose
  2. Copy all the property of argument into private variable
  3. Return the public function from module that you want to export. we can now use private variable inside public function and return it. 

Factory design pattern in node.js:
Now, we can see that correct object is created by updating the scope. But, this is probably not a correct way to create module. We should take help of constructor to create object.

So, create a constructor Project and use this to declare all the public variables and functions.
We can also create instance in "module.exports" which can act as factory. we can pass a type and based on the type a constructor can be called. Creating instance at run-time with above method is known as factory pattern.


If we do not wish to create factory design pattern, we can simply assign "Project" to module.exports.
This way we can create instance later as per our need and set or get values.

Monday, June 29, 2015

Non-blocking, require and modules in node.js

node.js is very close to JavaScript and it's also server side JavaScript. We can run js files once we have node installed in our machine using:

node app.js 

There are lot of differences too between node and JavaScript. node.js does not use "window" as a global variable, but it uses "global" as global variable. However, console is common object which is used across both of them. 

node is Non blocking: 


nodejs is non-blocking means if we create a server using node.js and are listening to any port, we can handle as many as request we want. Server will not blocked to a particular request, it can get request from all other client with out getting blocked. Same is true for any database request. 

require in node: 

require is used to import any module in node. It searches the file, folder or core modules to import. Order of searching for module is as follows: 


Let say we import module using require('./info') 
  • node will search for info.js file for module, if found then it will import it's functions 
  • If file with info.js is not found, node will look for folder with info name followed by index.js in that that folder 
  • If module is imported like require('info'), node will consider it as core module or project level module 

Module in node: 


We can create module in node using module.exports or exports.function_name . Setting module.exports allows the database_module function to be called like a function when required. Simply setting exports wouldn't allow the function to be exported.  
Example: 

Method 1: The following code will allow the user to call the function 




Method 2: The following code wouldn't allow the user to call the function, but call it using object 


Saturday, June 27, 2015

Pros and cons of different data structures

Arrays - 
Pros:
1. Access to an array element is fast since we can compute its location quickly.

Cons:
1. If we want to insert or delete an element, we have to shift subsequent elements which slows our computation down.
2. We need a large enough block of memory to hold our array.
3. Easily corrupted (One can easily inset data in middle)


Linked Lists - 
Pros:
1. Inserting and deleting data does not require us to move/shift subsequent data elements.

Cons:
1. If we want to access a specific element, we need to traverse the list from the head of the list to find it which can take longer than an array access.
2. Linked lists require more memory.
3. Easily corrupted (One can easily inset data in middle)


Stack - 
Pros:
1. Helps manage the data in particular way (LIFO) which is not possible with Linked list and array.
2. When function is called the local varriables are stored in stack and destroyed once returned. Stack is used when varriable is not used outside the function.
So, it gives control over how memory is allocated and deallocated
3. Stack frees you from the burden of remembering to cleanup(read delete) the object
4. Not easily corrupted (No one can easily inset data in middle)

Cons:
1. Stack memory is limited.
2. Creating too many objects on the stack will increase the chances of stack overflow
3. Random access not possible


Queue - 
Pros:
1. Helps manage the data in particular way (FIFO). which is not possible with Linked list and array.
2. Not easily corrupted (No one can easily inset data in middle)

Cons:
1. Random access not possible


Tree - 
Pros:
1. Searching is faster (with some ordering e.g., BST). we can search for a given key in moderate time (quicker than Linked List and slower than arrays).
2. Insert/delete keys in moderate time (quicker than Arrays and slower than Unordered Linked Lists).

Cons:
1. High overhead
2. Large waste of unused links
3. Predetermined limit on number of a node’s children

Heap - 
Pros:
1. When the data in the variable is needed beyond the lifetime of the current function.
2. It can offer the maximum memory an OS can provide

Cons:
1. You must make sure to free the memory when you are done

Graph - 
Pros:
1. Finding the path in efficient way

Cons:
1. High overhead
2. Large waste of unused links

Thursday, June 25, 2015

Introduction to Browser Internals

V8, webkit are now common terms used in web development. But, are we able to connect dots between these terms?

How browsers render HTML, CSS and JavaScript and what all are the other tasks
of browser. Once we get deep understanding about browser internal, we make better decision
moving forward in web development.

Gecko and Webkit are different rendering engines. Gecko-based browsers use
SpiderMonkey as their JavaScript engine, while WebKit-based ones use either
JavaScriptCore or V8. Rendering engines are responsible for rendering of HTML,
images and PDF etc. on page.

Following are the mostly used browsers and their rendering engines:

Internet Explorer  - Trident
Firefox - Gecko
Safari - WebKit
Chrome and Opera (from version 15) -  Blink (derived from WebKit)

Here is the diagram explains high level structure of browser:



Rendering process:

1. Generation of DOM tree - Rendering engine takes HTML from networking layer, parses it and converts it to tree format.
2. Generation of render tree - Rendering engine takes internal and external
css and combines with visual HTML to form another tree structure. Render tree
also contains color and dimensions information.
3. Generation of layout in render tree - This step will decide the co-ordinate
to each node. So, Render tree will contain the co-ordinate information as well.
4. Painting - Finally, render tree will be traversed and painted using UI
backend layer.

Process of parsing: Output of parsing is parsing tree and It involves 2 steps:

1. Lexical Analysis - Converts input to tokens (language vocabulary symbols).

Example of vocabulary:

INTEGER: 0|[1-9][0-9]*
PLUS: +
MINUS: -


2. Syntax Analysis -  Verifies the token with syntax rules, if rule is matched
the it will be added to parse tree.
Example of syntax rule can be term followed by operation followed by term
(term operation term).

Example of syntax:

expression :=  term  operation  term
operation :=  PLUS | MINUS
term := INTEGER | expression

After the parsing, parsed document is sent to compiler which is responsible
to convert it into machine code.

WebKit uses two well known parser generators: Flex for creating a lexer and Bison
for creating a parser

Language given in above example is simple since it's Grammar is defined. There are parser generator present that can take above grammar and generate parse for you! So, above language is context free language since it's grammar is defined.

But, HTML is not a context free language since there are many cases when syntax of HTML is incorrect still the page renders. HTML parser validates wrong syntax as well so that page renders. It makes it HTML parser much more complex since there are so many cases to handle.

There is no grammar defined for HTML parser, but specification is defined in HTML5 which is also known as DTD (document type definition). Output tree is DOM for which also specification is defined. DOM contains document, body and other nodes in tree format as shown below:



HTML5 parser cannot use top down or bottom up parsing due to it's forgiving nature. It uses a custom parser which involves tokenization and tree construction. Tokenization takes character from network and converts it to token which is then sent to tree construction step.



1. Tokenization algorithm:

<div>Hello World</div>

  • Initial state is "data state"
  • when < will encounter it will move to "tag open state", determines tag is open
  • when character from a-z will encounter, it will move to "tag name state"
  • when > is encounter it will move to "data state" again
  • Now, it will capture the data "Hello World"
  • Once < start again it will move to "tag open state" and if it is followed by /, determines tag close

2. Tree construction Algorithm: Receives tokens from tokenization step and creates dom.

Basic algorithm works as below:

  • initial mode
  • before html mode
  • before head 
  • in head
  • after head
  • in body
  • after body
  • after after body

If head tag is not present in html, it is created by default and move to next step (body in).

HTML parser never gives an error and it handles following scenarios and so many  others as well:

  • <br> or </br> both are allowed
  • If there is a table inside table, but not inside td, parser will place table as siblings.
  • Second form is ignored in case of nested forms
  • Parser will only allow same nested element 20 times maximum
  • Close html and body tag if not closed
CSS Parser: Unlike HTML, css is context free language. Lexical grammar and syntax grammar is defined in case of css. Webkit users flex and bison parser to parse in bottom up fashion. CSS style sheet is parsed into stylesheet object which has following structure:




Layout Process: This will decide the co-ordinate that is how the elements will render.
1. Parent determines it's own width
2. Parent height is dependent of child height

Painting: CSS2 defines the order of rendering as below:
  1. background color
  2. background image
  3. border
  4. children
  5. outline
The box are stored in stack and ordering is determined by z-index. If they have same z-index the foremost will be drawn.







Tuesday, June 23, 2015

Send E-mail using PHP and AngularJS

Implementing contact form in your website is a nice feature. The data of contact form can be stored in database or directly sent as e-mail.


Here are the steps to create e-mail contact form using php and AngularJS:
  1. Setup a gmail account to receive the contact e-mail. You can also setup Outlook or other account and change the below configuration accordingly.
  2. Create a page for contact form:
  3. We will including bootstrap.min.css and bootstrap font (//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet) in html first.
    Observe the following points in below code:
    • ng-submit="processForm()" will call preocessForm function
    • ng-class="{ 'has-error' : errorName }" is used for binding the error to class
    • Name, e-mail and content input field and Submit button.
    • formData.name, formData.superheroAlias and formData.content model created for name, email and content



  1. Set up JS - Observe following points in the code:
    • $scope.formData used to make glue between model and controller
    • $scope.processForm function making request to index.php to validate and send the e-mail
    • On success, the successful message and on failure, the error is assigned to property




  1. Set up PHP file - Observe following points in the code:
    • class.phpmailer.php is included and referred to send the mail
    • Validation of the values
    • $mail object and its property
    • If input field is valid then send the e-mail
    class.phpmailer.php will also using other classes, so we need to include class.phpmailer.php, class.pop3.php, class.smtp.php and PHPMailerAutoload.php.