Saturday, November 16, 2019

Why you should go for Node.js ?

If you are a Web or Software developer who works for a web platform, I am sure you already have some knowledge about Node.js. After complete reading this article, you will know about What is Node.js Why is it so great Why a developer should learn the Node.js
What is Node.js ?

Ryan Dahl is the original author and introduced Node.js in 2009 for the first time.

Node.js is an open-source and a cross-platform runtime environment that may be used for creating server-side, media applications and desktop application(along with electron).




Node.js improves the throughput and scalability in application with many input/output operations. It also suits for real time games which requires a lot of concurrent connections.
Node.js is made on Chrome's JavaScript runtime (V8 JavaScript engine), which helps to make the fast network applications. It uses an event-driven, non-blocking I/O model, which makes it lightweight and highly scalable, as well as well-suited for data-intensive real-time software that run across dispersed devices. Node.js applications are written in JavaScript and can be conducted over the Node.js runtime on various platforms -- Mac OS X, Microsoft Windows, Unix, and Linux. Why Node.js so great ?
There are various reason which makes Node.js simply great



Asynchronous Api
APIs of Node.js library are all asynchronous, i.e., non-blocking. It only suggests that unlike PHP or ASP, a Node.js-based server does not wait to get an API to return the data. After phoning it, the server goes on to another API. The Node.js has a telling mechanism (Event mechanism) that after calling the API, it does not need to wait for an immediate response, the program can proceed further. Super Fast
Owing to the above reason in addition to the fact it is built on Google Chrome's V8 JavaScript Engine, the Node JavaScript library is extremely fast in code execution. Single-threaded yet exceptionally Scalable
Node.js utilizes a single-threaded version with occasion looping, in which the exact same program can guarantee service to a far larger amount of requests compared to typical servers such as Apache HTTP Server. Its Event mechanism assists the server to respond immediately in a way that is non-blocking, eliminating the period. This produces the server exceptionally scalable, unlike traditional servers which create restricted threads to handle requests. Why developer should learn Node.js ?
Since its inception, it has come a long way, Node.js is highly stable product now. The giant internet company is using this product, like, it is used by LinkedIn since the evolution of time has decreased. Netflix uses it because this has enhanced the program's loading time by 70%. Uber, PayPal, IBM, eBay, and Microsoft use it.

These days, a lot of start-ups, too, have jumped onto the bandwagon in including the Node.js with other JavaScript Framework as part of the technology stack. There are many opportunities outside there, I certainly can say there were such Node.js developer demand never before. If you have fundamental knowledge of JavaScript you can easily start to learn Node.js. There is tremendous community support for this product. We can easily get almost any Node.js module as free, we can easily find the documentation and tutorials. So learn Node.js and get the best opportunity from the current IT industry.

The author credit goes to David Atulegwu

Sunday, February 25, 2018

Best Handlebars tutorial with demo

What will you get from this article?

When you will finish to read this article, you'll know client-side templating and how to do this with Handlebars.js, and how it worths to give a try.
You will explore main features of Handlebars.js for better templating, like, built-in helpers/custom-helpers to add the logic in your template, partial for modularizing the code, and precompile the templates to increase the dom rendering speed and automation of precompiling process with Grunt.


What’s client-side templating?

Before dive into the Handlbars.js, we need to understand what is client-side templating first. Every experience web developer might have some experience of writing JavaScript to generate HTML, something like,
    var person = {name:suman, age : 30} 
    var elem = document.createElement('div');
    elem.innerHTML =  'name=' + person.name + ' age=' + person.age
    result.appendchild(elem );
    
Now, think of above code as thousands line on the large and complex project, it would be error prone, sluggish, and hard to maintain. We need to separate those UI JavaScript codes with the tool which is easy to use, maintain, and flexible.

After using templates on the projects, a person works on it does not need deep programming to make UI better, because template file is similar to HTML which is easy to modify via changing the tags, attributes and the position of tags.

For example, above code can be written in Handlebars something like
name = {{ name }} age = {{age }}
So client-side templating is the tool to use the generate HTML using provided data with its own syntax. All we do this to separate the data and presentation code.

After using templates on the projects, a person works on it does not need deep programming to make UI better, because template file is similar to HTML which is easy to modify via changing the tags, attributes and the position of tags.

What is handlebars.js?

hanldebars tutorial

Handlebars is an open source JavaScript template engine which is inherited from Mustache.js, is used to separate the UI code from the business code. It's semantic template
language, which means, the HTML is created as a string, would be inserted in your web page.

For example, the template code <h3>{{site}}</h3> would be converted to <h3>smashingmagazine.com</h3>, and ready to use at the web page. It's famous for client-side templating but this can be used on server templating as well, in this article we will focus on the client.
The Handlebars syntax is quite similar to syntax of other templates-engine, like,

Mustache.js
var context = {site : smashmagzin.com };

{{site}}


Dust.js
var context = {site : smashmagzin.com };

{site}


Handlebars.js
var context = {site : smashmagzin.com };

{{site}}


In Handlebars.js, the {{site}} expression fetches the data from context while compiling and outputs as  <h3>smashmagzin.com</h3>.

Why should we use handlebars.js?



Handlebars is very easy to use and flexible, it's built on top of Mustache, it supports all Mustache syntax which is known for logicless templating while using Handlebars helper, you can add the logic to your template for flexibility. You can use the built-in helper like if, unless, each(loop helper) and can create the custom helper.
You can precompile the templates into single JS file to increase the faster dom rendering. As compared to Mustache templates, it's 5 to 7 time faster by using precompiling. The feature like partial can be used to modularize your HTML/UI code. The Handlebars is using within top tools like Ember.js and hbs(template engine) of Express.js. It's fast-growing and widely community supported template engine. As of writing, 141 contributors, 1675 forks and 12994 stars on Github prove that. The Handlebars supports in all major browsers, like, Chrome Firefox, Safari and Internet Explorer.

How to use handlebars with the simple demo?

To use the Handlebars, you need to add a single file handlebars.min.js in your web page and start writing your template, below is the simple demo,

See the Pen handlebars-simple-demo by suman bogati (@sumanbogati) on CodePen.


We define the templates in a script tag and its type is “text/-x-handlebars-template”, by doing so the template content does not display into a browser.

Compiling the templates by Handlebars.compile(elem) returns the function which accepts the data-context as the parameters, now it can be invoked by passing the actual data, and finally, this function returns the string of HTML.

Important features

The template is a successor of Mustache, It supports all the features that Mustache has, and it's additional features make it very flexible and robust tool.

Expression converts ideas in reality
The name/property exists between the curly braces is the expression. Using the expression in Handlebars template, you can get the data from context object, we already have seen the use of an expression in above points.

Data
var context = {lang: english, country: England} 
View presentation
Speaking is = {{lang}}  of {{country}}
lang and country are expressions which are overridden by the data/values english and england after compiling the template.

The value returned by an expression {{propname}} is html-escaped, which means, if you write  {{<h2>hello world </h2>}}, then it outputs <h2>hello world </h2> as result, handlebars does not execute html to prevent XSS attack. 

But there might be the case where you need to execute the HTML code, where you can use triple curly braces {{{...}}} enclosing a variable, like  {{{<h3>Smashing magazine</h3> }}}, which outputs the header Smashing magazine. 

Now you might have a question that what about XSS attack? Handlebars.SafeString() rescues you from this situation, you need to do just new Handlebars.SafeString( {{{<h3>Smashing magazine</h3> }}}) and you are secure.

There is two type of expression: one, the header example at above is single expression;  other is block expression which has two pairs of curly braces opening and closing, like
{{#if homePage}}
   
{{productList}}
{{/if}}
As you can see, the if has the opening and closing tag. In this block expression, homePage looks up 'true' value in current context.

Helpers respone your query

Helpers are used to adding logic in your template, there is two kinds of helper one is built-in other is custom helper which can be created by the user.


Built-in helpers are: {{ #if...}} {{/if}}, {{ #unless...}} {{/unless}} and {{ #each ...} {{/each}}
'
{{#if ...}} helper is used to add the logic of if condition in your template, for example, you want to display the “thank you” message if form is submitted already, like
{{#if formSubmit}}
    

Thank you {{user}}, for submit the form,

{{/if}}
Above block will be executed if formSubmit is true.

In case of form not submitted, you can use the else condition to display the form, when all come together it looks like,
{{#if formSubmit}}
    

Thank you {{user}}, for submit the form,

{{/if}} {{#if formSubmit}}

Thank you {{user}}, for submit the form,

{{else}}
form content here.. .
{{/if}}
{{#unless ...}} is opposite of {{#if ...}}, the condition is true when a variable with “unless” returns the falsy value like, the below block will be rendered when “formSubmit” is false,
{{#unless formSubmit}}
    
form content here..
{{/unless}}

{{#each ...}} helper is used to repeat your template with provided data, for example in below demo,
the loop helper is used to iterates the item of array(people)

See the Pen Handlebars-each-helper by suman bogati (@sumanbogati) on CodePen.

Custom Helper

You can create your own helper with handlebars, suppose, in a template, you need the function
that will fetch the relative string from language object using the provided key.
var langEn = {
  success : 'The file has been uploaded successfully'
}

var getString = function (key){
   return   langEn[key]
}
Handlebars.registerHelper('getString');

{{#getString success}}

The result for {{#getString success}} would be “The file has been uploaded successfully”.
Partial simplifies your life

Partial is used to modularize the template code which eventually will be rendered as html, its handy when we work on large and complex project. You can reduce the template code using the partial, for example, header and footer are similar to all web pages of a website, so you can create this in partial and use it wherever you want. The below example is shown with two different template files,
Header Template (header.hbs)

Main Template (main.hbs)
{{ >> header }}
JavaScript
Handlebars.registerPartial('header ', Handlebars.getTemplates('header'));
As you can see in above example, you can use the header partial at the place you want by locating {{ >> header }}, now you might have imagined already how much its helpful to make template code modularize, easy to use, and maintainable. You can register the partial with Handlebars.registerPartial() function and can be invoked it by using {{ >> partialName}} like we have done with the header in above example.
Precompiling saves your resources
Many templates-compilation on the fly could be the performance bottleneck and cause as slow rendering in the browser. So you can precompile all template code into single JS file on your machine first, which drastically improves the rendering performance. This feature takes Handlebars ahead than other template engines.
How to precocmpiling the template?
For precompiling the template you need to install following tools on your machine:
  1. You can find how to Install nodejs on your system.
  2. After installing nodejs, next, install Handlebars.js npm package by
  3. npm install handlebars -g
  4. Now you can precompile the templates by executing the following command from your project directory
  5. handlebars <input> -f <output>
In above command, an input is template file and output is the template-converted-js file, that JS file can be added to your webpage and can be rendered as HTML without compiling on the fly.
You can save the time and effort by automating all this process, so, what's needs to be done for this?

We already have Node.js and Handlebars.js npm package
  1. Next, install grunt in your project directory by
  2. sudo npm install grunt --save-dev
  3.  Next, install the grunt-handlebars.js plugin which precompile the templates  (.hbs to .js), 
  4. npm install grunt-contrib-handlebars --save-dev 
Here .hbs is your template files which will be converted at JavaScript functions in a JS file.
Next, you can configure Gruntfile.js in your project directory, like the location of your templates file and location of converted JS file.
handlebars: {
    // converting all .hbs(handlebars templates file ) into all.js file
    all: { files: { "js/all.js": ["templates/*.hbs"]}} 
}
Here is the sample Gruntfile.js which you can use in your project directory, don't forget to edit according
to your requirements. After setting up this, go to project directory by cd in terminal/command-prompt, now you can type the grunt to pre-compile the templates to all.js file.
Conclusion
In modern days of web development, it becomes essential that creating new features, fixing bugs and enhancement of existing feature should be performed on high speed, for that your code need be organized, readable and easy to maintain.
Using template engine you can ensure that your UI code is separate from business code, Handlebars helps you to modularize the code, fast dom rendering and add extreme flexibility to your template with great features.
What's next?
You can find more about Handlebars.
TryHandlebars gives the opportunity to practice online.
Want to participate as a contributor, find the Handlebars at Github.

Saturday, January 6, 2018

How to display PDF in a web page directly from Github?

Problem

This does not work when you try add this https://github.com/sumanbogati/images/raw/master/sample2.pdf  PDF-Url to your a web page, today we will know how to display PDF into a web page directly from Github.

The process of displaying PDF directly via Github

pages.github.com is used to create the static website and interestingly, the content of that website is served from the Github repository. You would create a repository on the Github, put the PDF under that repository/website, and give the URL of PDF on your website for displaying the PDF.

How to create a static website using Github?


Make the static website by creating the repository using your Github username, For example, if your username is sumanbogati, then you should create the repository named sumanbogati.github.io, When you land this sumanbogati.github.io into the browser, it shows the content of index.html of this repository. 

The below image gives some light on how to create a static website using your Github username, more details can be found at HERE



After creating the repository/website, now you need to put the PDF on that repository through the interface or command line. If you just place the PDF on a root of repository, then a PDF-Url would be something like,


If there is a PDF inside directory under the root of repository, then PDF-Url would be like,


Now you can use the HTML tag like embed, iframe or object for displaying a PDF on a web page.

<embed src="https://sumanbogati.github.io/dirname/sample.pdf" type="application/pdf" />

You can find the demo HERE.

Monday, December 25, 2017

How to display PDF in html web page

Usually, we need to display PDF file in HTML web page, today we will learn how do we embed the PDF file in a web page. There are many ways to do this. It's important to understand the best approach that suits your needs. Following are super easy methods for adding the PDF to your Website. 1. <embed />
<embed src="https://sumanbogati.github.io/tiny.pdf" width="600px" height="500px" />
Pros:- No JavaScript required, HTML standard, and Easy to use. Cons:- It does not have a fallback when your browser is not able to display PDF. DEMO 2. <object> </object>
<object data="https://sumanbogati.github.io/tiny.pdf" type="application/pdf" width="600" height="500">
  test.pdf
</object>
Pros:- No JavaScript required, HTML standard, and Easy to use. If a browser does not display the PDF then it let the user download the PDF by fallback. DEMO

3. <iframe> </iframe>
<iframe src="https://sumanbogati.github.io/tiny.pdf" style="width:600px; height:500px;"></iframe>
Pros:-
No JavaScript required, HTML standard, and Easy to use. You can reach the maximum users using a iframe.
DEMO

To cover the maximum browsers
, you can use the following code
<object data="https://sumanbogati.github.io/tiny.pdf" type="application/pdf" width="600" height="500">
    <embed src="https://sumanbogati.github.io/tiny.pdf" width="600px" height="500px" />
        

This browser does not support PDFs. Please download the PDF to view it: Download PDF.

</embed></object>
To reach the android browser

Any of the above method, does not display PDF in android browser, for that you need to upload the PDF to google drive and share that document with everyone, now you get the link and use this URL with embed tag, eg:-
<embed src="https://drive.google.com/file/d/1ZKgZhUuBr_-nLnbpExhQmqKCx_1QqxT2/preview" width="800px" height="1000px" />
We will reach to all the Desktop and android browsers
by following code,
<object data="https://drive.google.com/file/d/1ZKgZhUuBr_-nLnbpExhQmqKCx_1QqxT2/preview"  width="600" height="500">
    <embed src="https://drive.google.com/file/d/1ZKgZhUuBr_-nLnbpExhQmqKCx_1QqxT2/preview" width="600px" height="500px" />
        

This browser does not support PDFs. Please download the PDF to view it: View the PDF.

</embed></object>

Advance way to display PDF in html web page,

If you want to display PDF in browsers of all devices(Desktop and android mobiles) and want more control over displaying PDF in html web page, then the pdf.js will be useful. Following are the reasons which might attract you to use pdf.js,

  • Control over PDF toolbar in browser, there can be the interface, by which, end user can zoom and navigate the PDF pages.
  • Some annotation over the displayed PDF.
  • Supports on all desktop and mobile browsers.
  • It’s secure, users are not able to download the PDF.
  • You can validate on html web page that PDF is rendered or not.
  • pdf.js is JavaScript library which is maintained by Mozilla, it's so reliable and community supported, that, even Opera browser uses this framework on their own browser.

DEMO

Conclusion

If you need to display simply a PDF and does not want more control over the PDF in browser then the mix use of object and embed tag will be fine, otherwise, pdf.js can be the great tool.

Friday, November 10, 2017

Best books to learn JavaScript

I would suggest using following JavaScript books for different learners.

If you are a beginner in JavaScript, the book A Smarter Way to Learn JavaScript will be perfect for you. The author of the book teaches the JavaScript in a unique way.

Most interestingly, this book helps you to learn JavaScript doing practical exercises, which is powerful and helpful for a beginner.

If you are looking for intermediate or advanced JavaScript learning, the book Eloquent JavaScript will be excellent. After reading each few chapters, you will get the project that needs to be done for actual learning.

This book has also chapters about latest technologies like Node.js, Canvas, and Web-socket related to JavaScript.

Other than that, the resources from Mozilla Developer Network can be useful, for example, if you would like to know about querySelector() method, you would just type querySelector mdn on google, most probably the top link from a result will be the resource you need.

Takeaway

After so many years of experience in programming, I could say with surety that practical knowledge would not come only by reading the book and online resources, for that you need to use what you have learned, it would not gain until your brain fight to solve the problem by coding in your favorite editor.

Sunday, November 5, 2017

Difference between undefined and null in JavaScript


Every JavaScript programmer uses the undefined and null in their programming career, but do we really know the difference between them.

Today I put some light on differences between undefined and null and which one we should use when we programming?


Definition

Variable undefined means it has been declared but did not assign real value yet(eg: string, number, boolean and object). This also means the value does not exist before the scope, for example,

var color; 
console.log(color);

With above code, we are trying to access the declared variable which has no value, so as a result, color is undefined.


Variable null (var country = null) means it has no values, if you go deeper this means it has 'no object values'. After initializing the variable with null, it expects from the program that 'country' will hold the object at later.


Javascript throws the variable/property is undefined,


When you try to access the variable which is declared but did not associate any value,

var name;
console.log(name); // name is undefined


If you explicitly assign the undefined value

var name = undefined;


When you try to access the object’s property which is not defined yet,

var mycar = {color:'red'}
if(mycar.name==undefined){
    console.log(mycar.name) // mycar.name is undefined 
}


When the function does not return anything, sum contains undefined in the following case,

var sum = function (){console.log(2+2)};


When a function is defined with parameters but it invokes without the arguments,

function subtract(val1, valu2){ console.log(val1 + val2)}


after invoking subtract(3), val2 is undefined in above function.


The variable seems to null,


When you explicitly assign a null value to variable or property of the object,


var mycar = null; and var office.employee=null;


When browser tries to access the element which is not available in DOM,

var firstElem = document.getElementById('header');


the element with the id 'header' is not available in the browser, so firstElem is null.


When I use undefined?

If we need to check undefined against variable explicitly, for example, one scenario could be
where a variable is not undefined but it might be the null, following statement could be used

if(name !== undefined ){
    // this is being executed even when name = null;
}


When I use null?

If we want to check the variable is undefined, 'no object values', or element is null, then we use null, for example, we issue the query to check the DOM existence.

var header = document.querySelector('#header');

From above code,  we can validate if the header has something by checking header is null or not.


Conclusion

With null and undefined, it seems we are checking the same thing (no values) with two different approaches, so which one we should pick?. I want to go with null because it can be used to check for both null and undefined of the variable, whereas other is used to check undefined only.

Below condition is true if the variable(
name) is not undefined and is not null.

if(name != null){
  // this is executed when variable name has anything but undefined and null
}