Skip to main content

Posts

Showing posts from August, 2018

Expressjs Middleware for Nodejs

In this article, I am going to show you how we can setup Express middleware on Nodejs .  Express  is a lightweight web application framework for Nodejs that provides a robust set of features for web and mobile applications. The following steps are used for working with Expressjs: 1. Create a folder on C:\ name it expressdemo 2. Move into that folder and run the following commands: npm install --save express npm install --save ejs 3. Once these packages are installed, then create a subfolder named "views" inside that expressdemo folder. 4. Create a simple "hello.html" file inside the "views" folder. 5. Now create  expressdemo.js in the "expressdemo" folder with the following code: var express = require('express'); var bodyParser = require('body-parser') var app = express(); app.use(express.static('public')); app.use(bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParse

Prototypes in Javascript

Almost all the Javascript objects are instances of Object. Every object inherits properties and methods from Object.prototype. The developer has the flexibility to add new properties and methods to objects. The following example shows how to use Prototypes in Javascript. function Person(name,salary,age){ this.name = name; this.salary = salary; this.age = age; this.DisplayDetails = function(){ var name = "Details of Employee\n"; name+="=============================+\n" name+="Name:"+this.name+"\n"; name+="Salary:"+this.salary+"\n"; name+="Age:"+this.age+"\n"; return name; } } var person1 = new Person("New Employee",25000,27); console.log("Name is:"+person1.name); console.log(person1.DisplayDetails()); In the above example we created a new Prototype named " Person " which has the following properties

Array.Filter vs. Array.Reduce

Array.Filter and Array.Reduce are pertinent functions in Javascript. They give lot of flexibility to the developer. 1. Array.filter This function helps to generate another resultant array after an expression is applied to each element of an Array. Let's take an example: let cities = ["Toronto","Vancouver","London","New York", "Las Vegas"]; var result = cities.filter((city)=>{ return (city.length > 8); }); console.log(result); The above code will filter cities based on the length of name of the cities. All the city names that have length greater than  8 characters will be stored in a new array.The output will be: [ 'Vancouver', 'Las Vegas' ] 2. Array.Reduce  This function executes the callback function once for each element in the array. It works with two main parameters i.e. accumulator, currentValue let numbers = [1,2,3,4]; var total = numbers.reduce((sum, no)=> {

Array.map Vs. forEach

This is one of the concepts where people get confused. Every one thinks that Array.map function and forEach for an Array is the same, but which is not. Lets try to differentiate: 1. forEach forEach can be used with any array to iterate through each and every value. It's just like using a traditional 'for loop' that starts with 1 and goes through the end element. let array = [10,20,30,40,50]; array.forEach((number)=>{ console.log(number); }) The above code will generate the following output. 10 20 30 40 50 2. Array.map The map function creates a new Array with the result of calling the given function or expression on every elements of the Array. var result = array.map((number)=>{ return (number * 2); }); console.log(result); The output of the code is: [ 20, 40, 60, 80, 100 ] In the above example we are trying to iterate through every element of Array and multiply it by 2. The resultant applied on every element will be also an

Connecting Nodejs to SQL Server with Knex ORM - Part III

In this final multi part post, I am going to show how to do "Delete" and "Update" records through Knex. 1. Using DELETE Delete is the command to delete record from the table. We should run delete query with where  condition which is normally based on Primary key. var knex = require('knex')({ client: 'mssql', connection: { user: 'sa', password: '123', server: 'localhost', database: 'lovely' } }); knex("dept").where("deptno","50").del() .then(function (count) { console.log(count); }) .finally(function () { knex.destroy(); }); In the above delete command, we are trying to delete a row which has "Deptno" = 50. In case the command is successful, it will return a Promise.resolve that has been captured in .then function. It will also return the count of records that were deleted. 2. Using UPDATE Update command

Promises in Nodejs

Promises are a method by which we can handle Asynchronous Requests in a better way. Normally a Promise has three output conditions: a. RESOLVED b. PENDING c. REJECT Just imagine a Promise that your father made, for buying a good phone. It would have three conditions: a. RESOLVED - Your father got you a new phone. b. REJECTED - You didn't get a new phone. c. PENDING - The promise is neither rejected or fulfilled, still you are waiting for the phone The following code shows how we can handle the Promises. function checkValue(x){ if(x > 100){ return Promise.resolve(x); } else{ return Promise.reject(new Error("the value is less than 100!")); } } var result = checkValue(200); result.then((value)=>{ console.log("The value of Result is:"+value); }) .catch(function(err){ console.log("The error is :"+err); }) The above code will generate the following: The value of Result is:200 T

Connecting Nodejs to SQL Server with Knex ORM - Part II

In this second part of the multiple part post, I am going to show how to insert data into table in SQL Server. knex("dept") .insert({ deptno: 50, dname: "New Department", loc: "Test Location" }).catch(function(err) { // All the error can be checked in this piece of code console.log(err); }).finally(function() { // To close the connection pool knex.destroy(); }); console.log("Record Inserted"); If you run this code, one record will be created in the Table with Deptno: 50. The following result is shown as per data in my table, if we run the Select query. { DEPTNO: 10, DNAME: 'ACCOUNTING', LOC: 'NEW YORK' } { DEPTNO: 20, DNAME: 'RESEARCH', LOC: 'DALLAS' } { DEPTNO: 30, DNAME: 'SALES', LOC: 'CHICAGO' } { DEPTNO: 40, DNAME: 'OPERATIONS', LOC: 'BOSTON' } { DEPTNO: 50, DNAME: 'New Department', LOC: 'Test Locati

Connecting Nodejs to SQL Server with Knex ORM - Part 1

Normally we connect Nodejs to the databases like SQLite, MongoDB, Postgres etc . In this multiple part post, I am going to show you, how we can connect Nodejs with Microsoft's SQL Server using Knex and run CRUD operations. 1. Installation of required packages In order to connect Nodejs to SQL Server with Knex, we will need following node packages installation: i. npm install knex ii. npm install mssql Once the packages are installed, we can write the following code to connect: //Code to KNEX connection settings. var knex = require('knex')({ client: 'mssql', connection: { user: 'sa', password: 'pwd', server: 'localhost', database: 'Test' } }); //Code to query the Table DEPT knex.select("*").from("dept") .then(function (depts){ depts.forEach((dept)=>{ //use of Arrow Function console.log({...dept}); }); }).catch(function(err) {

Arrow Functions / Lambda Expressions

Arrow Functions or Lambda expressions were introduced in ES6 . Almost every modern language like C#, Java etc. have this feature. In very simple language we can say that Arrow functions are the expressions that help us to define functions and assign them to a variable. Let's try to understand the Arrow functions with the following example: //With no argument var firstFunc = ()=> { console.log("This is a demo of Arrow functions / Lambda Expressions") } firstFunc(); //With one argument var secondFunc = (a) => { return a*100 } console.log(secondFunc(20)); //With Two Arguments var thirdFunc = (a,b) => { return (a+b) } console.log(thirdFunc(10,90)); The above example create three arrow functions with one argument, two arguments and without any arguments. The out of the program will be: This is a demo of Arrow functions / Lambda Expressions 2000 100 For personalized coaching, contact: dhandrohit@gmail.

Spread Operator in Javascript

Spread Operator is a magical operator that is used with three dots i.e. "..." This is can be used with Arrays or Objects. It's primarily used to extract values of the Arrays or the properties of the Objects function demo(){ var cities = ["Toronto","Vancouver"]; console.log([...cities]); var t = { name: "Rohit", cities : [...cities] } console.log({...t}); } demo(); If we run the above program, the following output will be generated: [ 'Toronto', 'Vancouver' ] { name: 'Rohit', cities: [ 'Toronto', 'Vancouver' ] } So we can see that there two different ways by which Spread Operator is used i.e. [] and {} For personalized coaching contact: dhandrohit@gmail.com Happy Coding !

Use of Var, Let and Const in Javascript

I have seen lot of people often making mistake in differentiating between "Var", "Let" and "Const" 1. Var (function scope) It's a keyword used to declare variables that have a scope of Function block. In case we define it globally, it will have a Global Scope Let's see how "var" works: function demo(){ var i = 10; console.log("The value of i is:"+i); } demo() console.log("Value of i after function call:"+i); In the above example, we are have defined a "var" within the function "demo()". So it means that it will be accessed only within this function. That's why the last line will give you an error as the scope of the variable is within the function. Var (Global scope) If we define the var at the top, it would have the global scope which means that it can be accessed in any function. var i = 10; function demo(){ console.log("The value of i is:&qu