Friday, September 23, 2016

Express JS Routing In Detail

Express JS Routing In Detail

Routing refers to the definition of application end points (URIs) and how they respond to client requests. For an introduction to routing, see Basic routing.
The following code is an example of a very basic route.
var express = require('express');
var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.send('hello world');
});

Route methods

A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.
// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage');
});

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage');
});
Express supports the following routing methods that correspond to HTTP methods: get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search, and connect.
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, app['m-search']('/', function ...
There is a special routing method, app.all(), which is not derived from any HTTP method. This method is used for loading middleware functions at a path for all request methods.
In the following example, the handler will be executed for requests to “/secret” whether you are using GET, POST, PUT, DELETE, or any other HTTP request method that is supported in the http module.
app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});

Route paths

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.
The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.
Query strings are not part of the route path.
Here are some examples of route paths based on strings.
This route path will match requests to the root route, /.
app.get('/', function (req, res) {
  res.send('root');
});
This route path will match requests to /about.
app.get('/about', function (req, res) {
  res.send('about');
});
This route path will match requests to /random.text.
app.get('/random.text', function (req, res) {
  res.send('random.text');
});
Here are some examples of route paths based on string patterns.
This route path will match acd and abcd.
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});
This route path will match abcd, abbcd, abbbcd, and so on.
app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});
This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.
app.get('/ab*cd', function(req, res) {
  res.send('ab*cd');
});
This route path will match /abe and /abcde.
app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});
Examples of route paths based on regular expressions:
This route path will match anything with an “a” in the route name.
app.get(/a/, function(req, res) {
  res.send('/a/');
});
This route path will match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.
app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

Route parameters

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
app.get('/users/:userId/books/:bookId', function(req, res) {
  res.send(req.params);
});
Since the hyphen (-) and the dot (.) are interpreted literally, they can be used along with route parameters for useful purposes.
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }
The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).

Route handlers

You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
A single callback function can handle a route. For example:
app.get('/example/a', function (req, res) {
  res.send('Hello from A!');
});
More than one callback function can handle a route (make sure you specify the next object). For example:
app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});
An array of callback functions can handle a route. For example:
var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

var cb2 = function (req, res) {
  res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);
A combination of independent functions and arrays of functions can handle a route. For example:
var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from D!');
});

Response methods

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
MethodDescription
res.download()Prompt a file to be downloaded.
res.end()End the response process.
res.json()Send a JSON response.
res.jsonp()Send a JSON response with JSONP support.
res.redirect()Redirect a request.
res.render()Render a view template.
res.send()Send a response of various types.
res.sendFile()Send a file as an octet stream.
res.sendStatus()Set the response status code and send its string representation as the response body.

app.route()

You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.
Here is an example of chained route handlers that are defined by using app.route().
app.route('/book')
  .get(function(req, res) {
    res.send('Get a random book');
  })
  .post(function(req, res) {
    res.send('Add a book');
  })
  .put(function(req, res) {
    res.send('Update the book');
  });

express.Router

Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
Create a router file named birds.js in the app directory, with the following content:
var express = require('express');
var router = express.Router();

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;
Then, load the router module in the app:
var birds = require('./birds');
...
app.use('/birds', birds);
The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.

Detail is here:



Thursday, September 22, 2016

Express Js Routing System

Basic routing system


Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.


Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Where:
  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.
This tutorial assumes that an instance of express named app is created and the server is running. If you are not familiar with creating an app and starting it, see the Hello world example.
The following examples illustrate defining simple routes.
Respond with Hello World! on the homepage:
app.get('/', function (req, res) {
  res.send('Hello World!');
});
Respond to POST request on the root route (/), the application’s home page:
app.post('/', function (req, res) {
  res.send('Got a POST request');
});
Respond to a PUT request to the /user route:
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user');
});
Respond to a DELETE request to the /user route:
app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user');
});
For more details about routing, see the routing guide.


Detail is here:
https://expressjs.com/en/starter/basic-routing.html

#This is a personal note of mine.



Tuesday, August 30, 2016

ECMA Script-6 Introduction

Introduction:



The JavaScript core language features are defined in a standard called ECMA-262. The language defined in this standard is called ECMAScript & this article covers the most recent major update & changes to the language: ECMAScript 6. ECMAScript is the core language of node.js

ECMA Script-6 Block Bindings

Block Bindings



Var Declarations and Hoisting:

Variable declarations using var are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where the actual declaration occurs; this is called hoisting. Consider the examples below:

function getValue(condition) {

    if (condition) {
        var value = "blue";

        // other code

        return value;
    } else {

        // value exists here with a value of undefined

        return null;
    }

    // value exists here with a value of undefined
}


Behind the scenes, the JavaScript engine changes the getValue function to look like this:
function getValue(condition) {

    var value;

    if (condition) {
        value = "blue";

        // other code

        return value;
    } else {

        return null;
    }
}

The declaration of value is hoisted to the top. The variable value is actually still accessible from within the else clause. If accessed from within the else clause, the variable value will be undefined because it hasn’t been initialized, its initialized only in If clause.

Block-Level Declarations:


1.Inside of a function
2.Inside of a block { \\code block }

Let Declarations
The let declaration syntax is the same as the syntax for var. You can basically replace var with let to declare a variable, but the limit is only the current code block. Here’s an example:

function getValue(condition) {

    if (condition) {
        let value = "blue";

        // other code

        return value;
    } else {

        // value doesn't exist here

        return null;
    }

    // value doesn't exist here
}


No Redeclaration:


If an identifier has already been defined in a scope, then using the identifier in a let declaration inside that scope causes an error to be thrown. For example:

var count = 30;

// Syntax error
let count = 40;

This next let declaration exaple doesn’t throw an error because it creates a new variable within the if statement. Inside the if block, this new variable shadows the global count but prevents access to it until execution leaves the block.

var count = 30;

// Does not throw an error
if (condition) {

    let count = 40;

    // more code
}

Constant Declarations:


You can also define variables with the const declaration syntax. Variables declared using const are considered constants, meaning their values cannot be changed once set. For this reason, every const variable must be initialized when declaration, as shown in this example:

// Valid constant
const maxItems = 30;

// Syntax error: missing initialization
const name;

Constants vs Let Declarations:


Constants are like let declarations which is block-level declarations. That means constants are no longer accessible once execution flows out of the block, const doesn't hoisted, as demonstrated in this example:

if (condition) {
    const maxItems = 5;

    // more code
}

// maxItems isn't accessible here

A const declaration throws an error when made with an identifier which is already-defined variable in the same scope. It doesn’t matter variable was declared using var or let. For example, consider this code:

var message = "Hello!";
let age = 25;

// Each of these would throw an error.
const message = "Goodbye!";
const age = 30;

Attempting to assign a const to a previously defined constant will throw an error, in both strict and non-strict modes:

const maxItems = 5;

maxItems = 6;      // throws error

It wasn't throws error in case of let. As example below:

let maxItems = 5;

let = 6;      // throws error

Declaring Objects with Const:


A const declarations for objects do not prevent modification of the objects. For example:

const person = {
    name: "Nicholas"
};

// works
person.name = "Greg";

// throws an error
person = {
    name: "Greg"
};

**Just remember: const prevents modification of the binding, not modification of the bound value.

The Temporal Dead Zone:


A variable declared with either let or const cannot be accessed until after the declaration. Follow this example:

if (condition) {
    console.log(typeof value);  // ReferenceError!
    let value = "blue";
}

Block Binding in Loops:


This is onne area where developers most want block level scoping of variables is within for loops, where the throwaway counter variable is meant to be used only inside the loop. For for this we have to use let not var, cause var is being hoisted. Follow the two exaples below:

for (var i = 0; i < 10; i++) {
    process(items[i]);
}

// i is still accessible here
console.log(i);                     // 10

The variable i is still accessible after the loop is completed because the var declaration gets hoisted. Using let instead, as in the following code to ignore this problem:

for (let i = 0; i < 10; i++) {
    process(items[i]);
}

// i is not accessible here - throws an error
console.log(i);

In this example, the variable i only exists within the for loop.

Functions in Loops:


The characteristics of var have made creating functions inside of loops problematic, because the loop variables are accessible from outside the scope of the loop. Consider the following code:

var funcs = [];

for (var i = 0; i < 10; i++) {
    funcs.push(function() { console.log(i); });
}

funcs.forEach(function(func) {
    func();     // outputs the number "10" ten times
});

It outputs the number 10 ten times in a row. The variable i has a value of 10 once the loop completes, and so when console.log(i) is called, that value prints each time.

To fix this problem, developers use immediately-invoked function expressions (IIFEs) inside of loops to force a new copy of the variable they want to iterate over to be created, as in this example:

var funcs = [];

for (var i = 0; i < 10; i++) {
    funcs.push((function(value) {
        return function() {
            console.log(value);
        }
    }(i)));
}

funcs.forEach(function(func) {
    func();     // outputs 0, then 1, then 2, up to 9
});

**Fortunately, block-level binding with let and const in ECMAScript 6 can simplify this loop for you.


Let Declarations in Loops:


On each iteration, the loop creates a new variable and initializes it to the new value with the previous same name. Consider the example:

var funcs = [];

for (let i = 0; i < 10; i++) {
    funcs.push(function() {
        console.log(i);
    });
}

funcs.forEach(function(func) {
    func();     // outputs 0, then 1, then 2, up to 9
})

For more clearance about the fact follow this example also:

var funcs = [],
    object = {
        a: true,
        b: true,
        c: true
    };

for (let key in object) {
    funcs.push(function() {
        console.log(key);
    });
}

funcs.forEach(function(func) {
    func();     // outputs "a", then "b", then "c"
});
In this example, the for-in loop shows the same behavior as the for loop. Each time through the loop, a new key binding is created, and so each function has its own copy of the key variable. The result is that each function outputs a different value. If var were used to declare key, all functions would output "c".


Constant Declarations in Loops:


The ECMAScript 6 specification doesn’t explicitly disallow const declarations in loops; however, there are different behaviors based on the type of loop you’re using. For a normal for loop, you can use const in the initializer, but the loop will throw a warning when you attempt to change the value. For example:

var funcs = [];

// throws an error after one iteration
for (const i = 0; i < 10; i++) {
    funcs.push(function() {
        console.log(i);
    });
}
In this code, the i variable is declared as a constant. The first iteration of the loop, where i is 0, executes successfully. An error is thrown when i++ executes because it’s attempting to modify a constant.

When used in a for-in or for-of loop, on the other hand, a const variable behaves the same as a let variable. So the following should not cause an error:

var funcs = [],
    object = {
        a: true,
        b: true,
        c: true
    };

// doesn't cause an error
for (const key in object) {
    funcs.push(function() {
        console.log(key);
    });
}

funcs.forEach(function(func) {
    func();     // outputs "a", then "b", then "c"
});

The for-in and for-of loops work with const because the loop initializer creates a new binding on each iteration through the loop rather than attempting to modify the value of an existing binding (here key is a, b and c).

Global Block Bindings:


Another way in which let and const are different from var. When var is used in the global scope, which is a property on the global object (window in browsers). That means you can overwrite an existing global using var, such as:

// in a browser
var RegExp = "Hello!";
console.log(window.RegExp);     // "Hello!"

var ncz = "Hi!";
console.log(window.ncz);        // "Hi!"

If you instead use let or const in the global scope, a new binding is created in the global scope but no property is added to the global object. That also means you cannot overwrite a global variable using let or const, you can only shadow it. Here’s an example:

// in a browser
let RegExp = "Hello!";
console.log(RegExp);                    // "Hello!"
console.log(window.RegExp === RegExp);  // false

const ncz = "Hi!";
console.log(ncz);                       // "Hi!"
console.log("ncz" in window);           // false

This capability makes let and const a lot safer to use in the global scope when you don’t want to create properties on the global object.

Summary of Block Bindings:


The let and const block bindings introduce lexical scoping to JavaScript. These declarations are not hoisted and only exist within the block in which they are declared. This offers behavior that is more like other languages and less likely to cause unintentional errors, as variables can now be declared exactly where they are needed. As a side effect, you cannot access variables before they are declared, even with safe operators such as typeof. Attempting to access a block binding before its declaration results in an error due to the binding’s presence in the temporal dead zone (TDZ).

In many cases, let and const behave in a manner similar to var; however, this is not true for loops. For both let and const, for-in and for-of loops create a new binding with each iteration through the loop. That means functions created inside the loop body can access the loop bindings values as they are during the current iteration, rather than as they were after the loop’s final iteration (the behavior with var). The same is true for let declarations in for loops, while attempting to use const declarations in a for loop may result in an error.

The current best practice for block bindings is to use const by default and only use let when you know a variable’s value needs to change. This ensures a basic level of immutability in code that can help prevent certain types of errors.

Monday, August 29, 2016

Xampp MySql starting problem fixed

Xampp V.3.2.2 Install করার পর Apache এবং Mysql ২ টাই রান করছিলো না,


Solve for Apache: Go to the config file for apache httpd.conf
Change the port from 80 to 88
Re-run apache. It will run



Solve for Mysql: Go to Command Prompt Windows+R then Type cmd
From administrator mode type 'sc delete mysql' & press Enter
Re-run Apache, Apache should run.

If still you can not access phpmyadmin
https://localhost/phpmyadmin/



Step 01: Stop Mysql from xampp control panel

Step 02

Then, Run Command Prompt & go to the 'mysql' installation directory. In my case, It's C:/xampp/mysql.

cd d:/xampp/mysql

Step 03
Then, locate 'resetroot.bat' file and to edit it with notepad, run the following command in the command prompt.

notepad resetroot.bat

Step 04

Find 'bin\mysqld.exe' in the .bat file & in the same line locate a text simliar to '--no-defaults'. Add the following text after leaving a space. Save the file.

–datadir=c:/xampp/mysql/data

Step 05
Now, run resetroot.bat using Command Prompt. Then, Start MySQL service using XAMPP Control Panel.

That's it. You can reach PhpmyAdmin. Thank You.