Tuesday, February 28, 2017

How To Detect HTTP Or HTTPS in JavaScript?

You can use location.protocol to detect the protocol that the site is using. Lets say we have the url https://www.example.com. We can use following code to detect if it has HTTP or HTTPS.
//output => https:

You can change the protocol of the site simply by using following logic:
var protocol = location.protocol === 'https:' ? 'http' : 'https';

//output => http

How to solve nodejs Error: listen EADDRINUSE?

In this post we are going to discuss about how to solve Node.js error: listen EADDRINUSE. EADDRINUSE actually means that the port number which you are binding to the server using listen() is already in use.

Error: listen EADDRINUSE means the port which you want to assign/bind to your application server is already in use. You can either assign another port to your application.

Or if you want to assign the same port to the app. Then kill the application that is running at your desired port.

If any application is already running on 3000 then you will get the below error (Error: listen EADDRINUSE). Here is the screenshot of error:

To solve this error either you start your node server on another port or close the program using that port. If you use lsof, you can see what process is bound to the port with lsof -i:3000, and then force kill it by grabbing the process id (aka pid) and kill it with a kill -9 $pid.

You'll only see it if you have permissions; if you're running lsof as a different user than the app, try prefixing lsof -i:$port with sudo to make sure you have adequate permissions.

What really helped for me was:
killall -9 node
But this will kill a system process.

Ref: https://teamtreehouse.com/community/hi-its-throwing-an-error-listen-eaddrinuse-3000-unhandled-error-event

Monday, February 13, 2017

What New ES6/7 Has To Offer?

This post will give you a quick introduction to ES6 (aka ECMAScript 2015). If you don't know what is ES6, it’s a new JavaScript implementation. If you haven't taken a look at ES6/7 yet you're missing out on some amazing advances to the JavaScript language.

Some of the important features of ES6/7 are below:
• let, const
• Template Strings/literals
• Arrow Functions
• Classes
• Destructuring
• Modules
• Native Promises
• Async Await
• Spread Operators
• Rest Parameters

Let + Const
In ES5, you declare variables via var. Such variables are function-scoped, their scopes are the innermost enclosing functions. In ES6, you can additionally declare variables via let and const. Such variables are block-scoped, their scopes are the innermost enclosing blocks.

let is the new var and block-scoped: they only exist in the block they are defined in.
var num = 0; //globally scoped

for (let i = 0; i < 10; i++) { //i is block scoped
  num += i;
  console.log('value of i in block: ' + i);

console.log('Is i defined here?: ' + (typeof i !== 'undefined')); //Is i defined here?: false 

Constants (also known as "immutable variables"), i.e., variables which cannot be re-assigned new content. const is single-assignment. const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards.
const foo;
    // SyntaxError: missing = in const declaration

const bar = 123;
bar = 456;
    // TypeError: `bar` is read-only

Template Strings/literals
Template literals are a new feature in ES6 to make working with strings and string templates easier. Template strings provide syntactic sugar for constructing strings. You wrap your text in `backticks` and you'll get the features described below.
• They can be multi-line. Finally!
• You can interpolate variables in them
• You can actually interpolate using any kind of expression, not just variables
• You can construct raw templates that don't interpret backslashes
// Basic literal string creation
`This is a pretty little template string.`

// Multiline strings
`In ES5 this is
 not legal.`

// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Unescaped template strings
String.raw`In ES5 "\n" is a line-feed.`

var today = new Date()
var text = `the time and date is ${today.toLocaleString()}`
// <- 'the time and date is 8/26/2015, 3:15:20 PM'

Arrow functions
Fat arrow functions, also known as just arrow functions are a brand new feature in ECMAScript 2015 (formerly ES6). Arrows are a function shorthand using the => syntax. Arrow functions serve two main purposes: more concise syntax and sharing lexical this with the parent scope. Arrow functions behave differently than traditional JavaScript functions in a number of important ways:
• Lexical this binding – The value of this inside of the function is determined by where the arrow function is defined not where it is used.
• Not newable – Arrow functions cannot be used a constructors and will throw an error when used with new.
• Can’t change this – The value of this inside of the function can’t be changed, it remains the same value throughout the entire lifecycle of the function.
var reflect = value => value;

// effectively equivalent to:

var reflect = function(value) {
    return value;
When there is only one argument for an arrow function, that one argument can be used directly without any further syntax. The arrow comes next and the expression to the right of the arrow is evaluated and returned. Even though there is no explicit return statement, this arrow function will return the first argument that is passed in.

If you are passing in more than one argument, then you must include parentheses around those arguments. For example:

var sum = (num1, num2) => num1 + num2;

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;

The sum() function simply adds two arguments together and returns the result. The only difference is that the arguments are enclosed in parentheses with a comma separating them (same as traditional functions).

When you want to provide a more traditional function body, perhaps consisting of more than one expression, then you need to wrap the function body in braces and explicitly define a return value, such as:
var sum = (num1, num2) => { return num1 + num2; }

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
You can more or less treat the inside of the curly braces as the same as in a traditional function with the exception that arguments is not available.

Because curly braces are used to denote the function’s body, an arrow function that wants to return an object literal outside of a function body must wrap the literal in parentheses. For example:
var getTempItem = id => ({ id: id, name: "Temp" });

// effectively equivalent to:

var getTempItem = function(id) {

    return {
        id: id,
        name: "Temp"
The concise syntax for arrow functions also makes them ideal as arguments to other functions. For example, if you want to sort an array using a custom comparator in ES5, you typically write something like this:
var result = values.sort(function(a, b) {
    return a - b;
That’s a lot of syntax for a very simple procedure. Compare that to the more terse arrow function version:
var result = values.sort((a, b) => a - b);
The array methods that accept callback functions such as sort(), map(), and reduce() all can benefit from simpler syntax with arrow functions to change what would appear to be more complex processes into simpler code.

ES6 Classes formalize the common JavaScript pattern of simulating class-like inheritance hierarchies using functions and prototypes. They are effectively simple sugaring over prototype-based OO, offering a convenient declarative form for class patterns which encourage interoperability. Classes support prototype-based inheritance, constructors, super calls, instance and static methods.
class someClass {
    constructor(name, age) {
        this.name = name;
        this.age = age;

    sayName() {

    sayAge() {

var myInstance = new someClass('dwayne', 27);
Class inheritance
class Child extends someClass {
    constructor(name, age) {
        super(name, age);
    // Override the someClass method above
    sayName() {
        // This will call someClass.sayName() triggering the old alert
        // Which will just display our name
        // This will trigger the new alert which has labels and our age
        alert('Name:' + this.name + ' Age:' + this.age);

var myChild = new Child('dwayne', 27);
As you can see, classes are extremely flexible especially when extending a base class and having the ability to easily override a parent method without needing to write any boilerplate logic to do so.
In the ES6 classes syntax we have access to a function called super() which essentially just calls the parent function depending on the context and then returns the result. Calling super.parentMethodName() from within a child class will call the base class you inherited.

Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

/*Destructuring objects*/
const obj = { first: 'Jane', last: 'Doe' };
const {first: f, last: l} = obj;
    // f = 'Jane'; l = 'Doe'

// {prop} is short for {prop: prop}
const {first, last} = obj;
    // first = 'Jane'; last = 'Doe'

/*Array destructuring*/
const iterable = ['a', 'b'];
const [x, y] = iterable;
    // x = 'a'; y = 'b'

// list matching
var [a, ,b] = [1,2,3];
a === 1;
b === 3;

ES6 is the first time that JavaScript has built-in modules. In ES6 each module is defined in its own file. The functions or variables defined in a module are not visible outside unless you explicitly export them. This means that you can write code in your module and only export those values which should be accessed by other parts of your app.

ES6 modules are declarative in nature. To export certain variables from a module you just use the keyword export. Similarly, to consume the exported variables in a different module you use import.

Let's create a simple module that has two utility functions:
1. generateRandom() : Generates a random number.
2. sum() : Adds two numbers.

Next, let's create a file named utility.js for the module:

 function generateRandom() {
    return Math.random();

 function sum(a, b) {
    return a + b;

 export { generateRandom, sum }
That's it! The export keyword on the last line exports the two functions. As you can see, the exported functions are listed in curly braces separated by a comma. You can also rename the values while exporting like this:
 export {generateRandom as random, sum as doSum}

Now, let’s see how to consume the exported values in a different module.

 import { generateRandom, sum } from 'utility';

 console.log(generateRandom()); //logs a random number
 console.log(sum(1, 2)); //3
Note the first line. This imports the exported values from the module utility. If you want to import a single value (for example sum), you can do it by writing the following:
import { sum } from 'utility';

You can also import the entire module as an object and access exported values as properties. So, we can modify our code as following:
 import 'utility' as utils;

 console.log(utils.generateRandom()); //logs a random number
 console.log(utils.sum(1, 2)); //3
Rest of the topics are coming soon.

References: Understanding ECMAScript 6 arrow functions
Learn ES2015
ES6 Template Literals in Depth
Understanding ES6 Modules

Tuesday, February 7, 2017

Automate Your Tasks Easily with Gulp.js Part 2

Determining Folder Structure
Gulp is flexible enough to work with any folder structure. You'll just have to understand the inner workings before tweaking it for your project.

source is the folder where we will do our work.
assets/stylesheets/style.css will be created by gulp when we process and combine our SASS files in source/scss.
The assets/javascript/bundle.js file will be created by gulp when we minify and combine all our JS files.

Writing Your First Gulp Task
Before we get right into the code I think it's very important to mention that gulp only has 4 top level functions.
gulp.task defines your tasks. Its arguments are name, deps and fn.

gulp.task('task-name', function() {
  // Stuff here

gulp.task('dependentTask', ['task-name'], function() {
  //do stuff after 'task-name' is done.
'task-name' refers to the name of the task, which would be used whenever you want to run a task in Gulp. You can also run the same task in the command line by writing gulp task-name.

gulp.src points to the files we want to use. It's parameters are globs and an optional options object. It uses .pipe for chaining it's output into other plugins.

gulp.dest points to the output folder we want to write files to.

gulp.src and gulp.dest used to simply copy files looks like:
gulp.task('copyHtml', function() {
  // copy any html files in source/ to public/

gulp.watch method that checks to see if a file was saved. gulp.watch like gulp.task has two main forms. Both of which return an EventEmitter that emits change events. The first of which takes a glob, an optional options object, and an array of tasks as it's parameters.
// Gulp watch syntax
gulp.watch('files-to-watch', ['tasks', 'to', 'run']); 
If we want to watch all javascript files and run the jshint task whenever a javascript file is saved, we just have to replace files-to-watch with the source/javascript/**/*.js, and ['tasks', 'to', 'run'] with ['jshint'].
gulp.watch('source/javascript/**/*.js', ['jshint']);
In the above code block, when any files in the source/javascript subfolders that have an extension of .js change, then the task jshint will be run against those files.

Once gulp is installed we have to give it some instruction so it knows what tasks for perform for us. But, first, we need to figure out exactly what tasks we need to run in our project.
Lint our JavaScript(check for errors) using jshint. We’ll also need a reporter for jshint to make the output nicely formatted and color coded.
Compile our Sass files.

Install Required Plugins
$ npm install --save-dev gulp-jshint jshint-stylish gulp-sass
This will install all of the plugins we will need and add them to our devDependencies in our package.json file like we did when we installed gulp.

Now we’ll add the lint task to our gulpfile.
/* File: gulpfile.js */

// grab our packages
var gulp   = require('gulp');
var jshint = require('gulp-jshint');

// define the default task and add the watch task to it
gulp.task('default', ['watch']);

// configure the jshint task
gulp.task('jshint', function() {
  return gulp.src('source/javascript/**/*.js')

// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
  gulp.watch('source/javascript/**/*.js', ['jshint']);
So lets step through what we’ve done.
We’ve rewritten our default task to have the watch task as dependency. What this means is that running
$ gulp
will run the watch task.

Now lets look at the new jshint task. It sources any .js files that exist in source/javascript or any of it’s subdirectories. So a file at source/javascript/courage.js would be picked up for the task just as well. These files are then passed into our gulp-jshint plugin, which then passes it into the stylish reporter to give us the jshint results.

We can run this task by doing:
$ gulp jshint

Alright, now what about that watch task. It's simple actually, if a change is detected in any of our javascript files, it runs the jshint task.

Now we’ll add the compile SASS task to our gulpfile.
Sass serves as a way to extend CSS giving support for variables, nested rules, mixins, inline imports, and more. For sass compilation we’ll use gulp-sass.
/* file: gulpfile.js */

var gulp   = require('gulp');
var jshint = require('gulp-jshint');
var sass   = require('gulp-sass');

/* jshint task would be here from above */

gulp.task('build-css', function() {
  return gulp.src('source/scss/**/*.scss')

// define the default task and add the watch task to it
gulp.task('default', ['watch']);

/* updated watch task to include sass */

gulp.task('watch', function() {
  gulp.watch('source/javascript/**/*.js', ['jshint']);
  gulp.watch('source/scss/**/*.scss', ['build-css']);
We can run this task by doing:
$ gulp build-css

We’ve only scratched the surface of gulp. Gulp can be as complex or as simple as you need it to be, and because it’s just code you can do just about anything you want as a task.

Sources and Ref: