Promise.prototype.then() : JavaScript then() method and how to use it
Javascript , Requests , Uncategorized / September 25, 2019

Q:  How to use then() and how to return a promise from a function and use then() ?   A: then() is a method in the Promise prototype that returns a promise and accepts two callback functions. One function is for the success and the other is for the failure case of the promise. If both arguments are not given or are not callback functions, still then the method would not generate any errors. For example, here we create a new promise.

promise .then() exists hence it is a promise. .then() allows method chaining.   Now we will see how to use then to return a promise It is incorrect to use then() this way as it should return inside the then also. Otherwise resolving the promise returned by then will give undefined.

    It is incorrect to use the function without returning the promise returned  by then()

    Returning the promise returned by then is the correct way of returning a promise from a function

    If there is some kind of logic to be applied, this is the correct way of using then()

 

Node.js – tools/packages/practices for building a secure,high performance API with quality code

Contents >Code standard and styling >Security >Performance         In this article, we will take a look at some important aspects to be considered while developing Node.js applications and the tools/packages/practices that can be used to achieve them. Understanding and using these will help you in building a secure web application that is well structured and well documented and has a very high performance. Code standard and styling Tool – Linters(ESLint/JSLint/TSLint) Linters are static code analyzing tools that check for static code issues like styling errors, poorly structured code and unsafe code. Linters help in implementing a certain set of coding rules and helps in avoiding static errors like an absence of strict type checking, mismatched import or undefined variable usage .Static code analysis is analyzing the code for errors/faults in coding rule implementation before running the code. Dynamic code analysis is performed after the running. The most commonly used styling modules are Airbnb/JavaScript and Github/JavaScript.You have to integrate the linting plugin to the editor you are using(eg – Visual Studio Code/Sublime text). The linter will show linting errors like the following.   ESLint and JSLint are used along with JavaScript. TSLint is used with TypeScript. An example…

Check for duplicates in JavaScript Array of Objects
Express.js , Javascript , Uncategorized / July 28, 2019

How to check whether an Array of Objects contain duplicates by key Consider an Array of student Objects with each object having a key id. We have to perform a validation whether multiple objects with the same Id is present in the Array or not.

The above are Arrays of student Objects, one with duplicate id value and one without duplicate id value. To get the  Ids present in the Arrays we need to use the map() Method

  Now we have two Arrays containing all the Id values of Objects.  The first one has unique Ids  and the second one has duplicate Id 42342.   To check for duplicates in Arrays, we can create a set from the array. Sets will only have the unique items in the array

  The second set only has 2 values as one of the values in the Array had a duplicate. So, on comparing the length of the Array and size of the Set  we can determine id  Array has duplicates or not  

  The whole code to check whether an Array of objects contain key-value duplicates will look like this. We can use this logic…

Web Storage – A comparative study of Local Storage,Session Storage,Cookies,IndexedDB and WebSQL
databases , Javascript , Uncategorized / July 10, 2019

Storages in browsers – Web Storage Web Storage is the storage mechanism that allows Web applications to store data in Web Browsers. The various storage types include Local Storage, Session Storage, Cookies, IndexedDB, Web SQL. These storages are supported by most of the modern-day web browsers and are standardized by the World Wide Web Consortium. Web Storage lets a web application to store data which in turn helps in the effective end to end functionality of the application. Upon inspecting and navigating to the storage in the browser console, we can see what are the various storage mechanisms supported by the browser and data stored in them. FireFox       Chrome Local Storage Local storage is a key-value store that stores values as string. The data stored in local storage does not have an Expiration date and will stay in the browser forever until we clear the browser data using settings or using Javascript. Up to 10MB of data can be stored in most of the browsers and it is 10MB for Local Storage and Session Storage combined in chrome.IE has 10 MB each. Local Storage follows the same-origin policy. The same-origin means that the Protocol(Http/Https), port and the host…

Set and Get Custom Response Header values using Angular 5 and Express.js – Node.JS

While working with Node.js and Angular, sometimes you might need to set some custom values in Response Header from the server-side and get these values in your Angular application. These values can be some tokens, keys or anything. This article is about completing this requirement. Server-side using Express.js and Node.js To set a custom value in the response header, you have to write the following code in your Express.JS server

Even if you set this token in the response header, to get this in your Angular application you need to allow these header values. The allowed default header values are Cache-Control Content-Language Content-Type Expires Last-Modified Pragma To allow your custom header value, you need to use the Cors module of Node.JS. To install the Cors module, use the following command.

Now the code to allow the customer header values with Cors module use the following code

Accessing the header values in your Angular 5 application   To get the header value in the application, you need to access the whole response object. For this, you need to add on observe: “response”  to the request options in the following way

When subscribing to the observable, you can get the…

Using express-validator to validate password to have minimum 8 characters including at least one special character and at least one number

Q How to use express-validator to validate passwords to have minimum 8 characters including at least one special character at least one number? A The regular expression used to validate a password which will follow the above-mentioned pattern is as follows

While using express-validator, we use  the chain method .matches() to check the input password against regular expression as follows

The above validator checks whether the request body of the post request has a password which is a minimum of 8 characters long, and contains an alphabet and a special character.   If there are any validation errors, it can be obtained using  validationResult(req)  

To display only the first error at a time we add the following object to errors.array() 

Now handling the error part looks like this

So the final code looks like this

 

Redis Tutorial Part 3 – Redis Data structures and working with Node.js ioredis

Redis Data structures Key-value stores mostly support string keys and string data but Redis does a lot more than that. Redis is not just a simple key-value string store It supports complex kinds of data structures, not just string. We will look more into this property of Redis in this tutorial and see how to utilize this using Node.js and ioredis module. Get the ioredis module installed on your app from https://www.npmjs.com/package/@types/ioredis   1 String – Basic kind of string. Lets us say the name of a person. We will see how we can store this value using ioredis We set value bar into key foo using set and get the value using get.

2 Binary Safe String – Can contain any type of data represented as a string: PNG images or serialized objects, for example. Here we have a base64 encoded data of an image.We store this data in redis.Remember a value can’t be bigger than 512 MB. base64 of png – iVBORw0KGgoAAAANSUhEUgAAACMAAAAjCAYAAAAe2bNZAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gUfFBM7nAl7igAAAPVJREFUWMNj1G/R/88wSAATwyACLMgcYzljojXefHmT4cvPLwzU1A93TJRpFEOZWxnRhj37+IzBa4oXA7n6b7y8wRAxJwK7Y3g5eBkYGBgYNl7ayPD843O8BmXYZjBI8UuhiMH0Ews0xDXwRxMDAwPDpoubGM4+OkvQMcM+AY86ZtQxo46hSXXAwMDA4Kfvx2AibzKwjvn84zMDAwMDg7+eP9HVATKA6SelOkEHjMhNCFJC5NmHZxgGUqqfcbQ9M9qeobQ9QyzA1Z4htj1EVHuGUkBJe2i0Ohh1zKhjRkZ7hlJASXuIhVrtEUrbQ6PtmdHcRA4AAAq6hb9r4YF9AAAAAElFTkSuQmCC

We can store buffer data as well in redis..

3 Lists – Collections of elements ordered according to the order of insertion

    4 Sets – Sets of data. Here we have a…

Filter array of objects having array of objects
Javascript , Requests , Typescript / March 20, 2019

Q: How to filter an array of objects having an array of objects Example object –

  A  –  When we consider the above object having an array of superheroes in members. Each superhero having an array of power. We need to get the superhero having the power 4/shield  in their power array, in this case We apply the filter function on the members array, then we apply filter function on powers array present in every item in the members array in the following way.

Gives output

On applying the filter function on inner powers array, if we get the length of the resulting array greater than 0, it means that the inner array contains the power4/shiled .  

logging in Node.JS – Express Application using Winston logger
Express.js , Javascript , Node.js , Typescript / February 20, 2019

Logging is keeping a record of all data input, errors, data output, and final results in a program. While developing an application, keeping track of responses, requests, errors, etc makes the development process more efficient. Keeping logs is also a part of code standardization. Logs can be displayed on the console and written to a file while working with Node.js.Here in this tutorial, we will learn how to create create a logger which keeps track of Request, Response, Errors and Time while building an ExpressJS application in Javascript/Typescript   Step 1 Install the Winston node package with the Node package manager

  Step 2 Create a logger.ts (.js file if you are working with  Javascript) preferably in a common folder outside, and add the following code to it  

In the above code, createLogger creates a new logger    

Adds Timestamp to your log. It defines formatting options  

Displays the log in console.  

Writes your error file to error.log and info to info.log    

If false, handled exceptions will not cause process.exit   Step 3 In your controller or where ever you want to create the log, import the logger file

Step 4…

Knockout – A comparative study against AngularJS
Javascript , Knockout , Uncategorized / September 14, 2018

Knockout js is a Javascript library which follows MVVM(Model-View-ViewModel) architectural pattern. Unlike the AngularJS framework, the knockout is a library. The structuring of your application is entirely up to you when using KnockoutJS whereas the framework does it for you while using AngularJS. AngularJS follows MVC architectural pattern where Knockout follows the MVVM architectural pattern. The latest Angular frameworks from Angular 2 to Angular 8 follows CBA(component-based architecture.Each component individually follows MVC architecture). Now let us see how AngularJS follows the MVC architecture. Model – The model represents and holds application data. Controller – The part of MVC which helps in the interactions between the Model and View. The user uses the controller. The controller manipulates the model. It is in the controller that we apply the necessary logic to our data and manipulates the model so that the change in data is reflected in the view. View – Represents what the user sees. The view gets updated when the controller manipulates the model. In AngularJS,$scope indicates the model. If Iwe add a new $scope.firstname in the controller , firstname is the model property and {firstname}} { binds the model to the view {{firstname}} – This is a type of data binding called interpolation…

Share this page in social media platforms