Posts

Showing posts from 2017

when to use prototypes

* For object creation optimization Built-in prototype object is if you'll be duplicating an object multiple times that will share common functionality. By attaching methods to the prototype, you can save on duplicating methods being created per each new instance. But when you attach a method to the prototype, all instances will have access to those methods * use prototypes if we need to declare a "non-static" method of the object. var myObject = function () { }; myObject.prototype.getA = function (){   alert("A"); }; myObject.getB = function (){   alert("B"); }; myObject.getB();  // This works fine myObject.getA();  // Error!

Inheritance in Javascript

Inheritance in Javascript Inheritance is when an object or class is based on another object (prototypal inheritance) or class (class-based inheritance), using the same implementation. function Person(name, age, gender, interests) {   this.name = name   this.age = age;   this.gender = gender;   this.interests = interests;   this.getName = function() {     return this.name;   } }; Person.prototype.getAge = function() {   return this.age; } /** Teacher inherit properties from the person class. Person.call(this, name, age, gender, interests ) after .call() properties are inherited in teacher class. */ function Teacher(name, age, gender, interests, subject) {   Person.call(this, name, age, gender, interests)   // Vehicle.call(this)   this.subject = subject;   this.getSubject = function() {     return this.subject;   }   this.getName = function(...

Timer unref ref in nodejs

Timers Unref, Ref in nodejs If there is no other activity keeping the event loop running, the process may exit before the Timeout object's callback is invoked when Calling timeout.unref() var timeout = setTimeout(function() { console.log('setTimeout') }, 10000); var interval = setInterval(function(){ console.log("exectute every 10 secs") }, 5000) After unref application will stop when other than this setInterval, nothing is running in eventloop interval.unref(); If I not ref again application will stop because other than this setInterval nothing is running in eventloop interval.ref(); /** * References : https://www.bennadel.com/blog/3301-calling-timeout-unref-with-settimeout-does-not-appear-to-be-a-best-practice-in-node-js.htm * References : https://nodejs.org/api/timers.html */

Npm install

Npm install npm install --save express npm install --save-dev mocha Package.json will be "dependencies" : { "express" : "^2.2.33" }, "devDependencies" : { "mocha" : "^2.83.0" }

compare password and sensitive data's in nodejs

previously I did like this to compare the sensitive data's function validatePassword(fromDbPassword, inputPassword){          if( fromDbPassword === inputPassword) return true;           return false; } There is an attack security attack called timing attack . Hackers try to crack the encryption algorithm using the way.  So How to compare password hackers cant use the timing attack V8,  JavaScript engine used by Node.js, tries to optimize the code you run from a performance point of view. It starts comparing the strings character by character, and once a mismatch is found, it stops the comparison operation. So the longer the attacker has right from the password, the more time it takes. function checkApiKey (apiKeyFromDb, apiKeyReceived) {  return cryptiles.fixedTimeComparison(apiKeyFromDb, apiKeyReceived)  } To solve this issue, you can use the npm module c...

Docker tutorials

Docker  Pull the image sudo docker pull ubuntu sudo docker run ubuntu apt-get install -y ping Then get the container id using this command: sudo docker ps -l Commit changes to the container: sudo docker commit   iman/ping  Expose the port  docker run -p 9200:9200 elasticsearch  Then run the container: sudo docker run iman/ping ping  www.google.com Ref https://stackoverflow.com/questions/19585028/i-lose-my-data-when-the-container-exits https://runnable.com/docker/binding-docker-ports

Responsive ui

To create responsive ui Following steps To set view port Html 5 tag This one sets width is device width size use media queries in css3 @media only screen and (max-width: 768px) {     /* For mobile phones: */      .header{        width : 200px;      } } Mobile orientaion view : Potrait / Landscape @media only screen and (orientation: landscape) {     body {         background-color: lightblue;     } }

Wrap external http request in node js

Wrap external http request in node js var http = require('http'); var url = require('url').URL; var shimmer = require('shimmer') var api = {} api.wrapEmitter = require('emitter-listener') var Origional = http.get; shimmer.wrap(http, 'get', function getWrap(get) {     return makeRequestTrace(get); }) function makeRequestTrace(request) {     return function trace(options, callback) {         var req = request.call(this, options, function (res) {             console.log('Response===================' , res)             shimmer.wrap(res, 'on', function onWrap(on) {                 return function on_trace(eventName, cb) {                     if (eventName === 'data') {                         on.call(this, 'data', func...

one way binding vs two way binding

Image
React is one way binding (Uni directional) and its used for View layer Angular is  two way binding and follows MVC pattern One-way binding (React) When properties in the model get updated, so does the UI. Only one watcher exist Virtual dom https: //www.codecademy.com/articles/react-virtual-dom http://reactkungfu.com/2015/10/the-difference-between-virtual-dom-and-dom/ Two-way binding (Angular js) When properties in the model get updated, so does the UI. When UI elements get updated, the changes get propagated back to the model. When angular sets up databinding two "watchers" exist

Application monitoring tool essentials and links

basic APM tool should monitor 1. Down time of the applications 2. Capture  the slow responses 3. Compare the response time metrics for before commit  vs after commit  4. Show distributed transactions (Call trace) 5. Alerting the security issues (Ex: If external library has the security issue then it should indicate the alert )  Good Nodejs  APM  tools https://www.appdynamics.com/ https://newrelic.com/ https://www.dynatrace.com/ https://opbeat.com/ https://www.instana.com/ https://traceview.solarwinds.com/ https://risingstack.com/

__proto__ vs prototype

The  __proto__  property of  Object.prototype  is an accessor property (a getter function and a setter function) that exposes the internal  [[Prototype]]  (either an object or  null ) of the object through which it is accessed. __proto__  is the actual object that is used in the lookup chain to resolve methods, etc.  prototype  is the object that is used to build  __proto__  when you create an object with  new : _proto_ var parent = {   color : 'white' } var child = {} child  = Object.create(parent) child.color //White parent.color = 'black' child.color  // 'black' because of _proto_ chain Prototype function   Soldier ( )   { } Soldier . prototype  =   {   weapons :   [ 'rifle' ,   'grenade' ,   'bayonet' ] ,   weaponOfChoice :   'rifle' } ; var  GIJoe  =   new   Soldier ( ) ; var  Ram...

Inheritance in nodejs

To inherit the properties we can use util.inherits method var util  = require('util') util.inherits(child, parent) /**  * Inherit the prototype methods from one constructor into another.  *  * The Function.prototype.inherits from lang.js rewritten as a standalone  * function (not on Function.prototype). NOTE: If this file is to be loaded  * during bootstrapping this function needs to be rewritten using some native  * functions as prototype setup using normal JavaScript does not work as  * expected during bootstrapping (see mirror.js in r114903).  *  * @param {function} ctor Constructor function which needs to inherit the  * prototype.  * @param {function} superCtor Constructor function to inherit prototype from.  */ exports.inherits = function(ctor, superCtor) {     ctor.super_ = superCtor;     ctor.prototype = Object.create(superCtor.prototype, {         const...

Install mysql in Zip format

Run mysql zip file in windows 1. First create the my.ini 2. Add the paths in myini file    [mysqld] # set basedir to your installation path basedir=E:\\mysql # set datadir to the location of your data directory datadir=E:\\mydata\\data 3. Run mysqld    It will find defaultly my.ini file.    mysqld   --initialize or --initialize-insecure      After completes it created some files in data folder 4. Run sql server    mysqld  --console    mysql -u root  //Default user root https://dev.mysql.com/doc/refman/5.7/en/windows-create-option-file.html Reset the password 1. Create file mysql-ini.txt and add these 2. Add contents  mysql-ini.txt   ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';   SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass'); based on versions Run command mysqld --init-file=D:\\docs\\databases\\sql\\mysql-5.7.10-winx64\\mysql-5.7.10-wi...

Bind , call, callback wrap in JS

var fs = require('fs'); /**  * Going to wrap the fs.readFile method to do this  */ //Make copy of the fs.readFile method var Original = fs.readFile; /**  Wrap the fs.read file, we can use two function one is apply and other is call  */  APPLY fs.readFile = function(){         var startTime = process.hrtime();     console.log('file read method started')     //In apply method pass the arguments as a array of values     var result =  Original.apply(this, arguments);     var endTime =  process.hrtime(startTime)     console.log(endTime)     console.log('file read method ended, total read time =>' + endTime)     return result; } CALL fs.readFile = function(){         var startTime = process.hrtime();     console.log('file read method started using call')  //function.call(thisArg, arg1, arg2, ...) ...

Two return statements in javascript

function test() {     try {         return 'mongo';     } catch (e) {         console.log('error', e)         return 'redis'     } finally {         console.log('finally it returns value as elastic not mongo');         return 'elastic';     } }

Sample data for JSON databases

For sample data for the json databases Movies data { "create": { "_index": "movies", "_type": "movie", "_id": "tt0468569" }} {"title":"The Dark Knight","year":2008,"rated":["PG-13"],"released":"2008-07-18","runtimeMinutes":152,"genres":["Action","Crime","Drama"],"directors":["Christopher Nolan"],"writers":["Jonathan Nolan","Christopher Nolan","David S. Goyer","Bob Kane"],"actors":["Christian Bale","Heath Ledger","Aaron Eckhart","Michael Caine"],"plot":"When Batman, Gordon and Harvey Dent launch an assault on the mob, they let the clown out of the box, the Joker, bent on turning Gotham on itself and bringing any heroes down to his level.","languages...

Javascript tutorials

Today I learned few things in javascript  check for null, undefined, or blank variables in JavaScript? if ( value ) { } will evaluate to  true  if  value  is not: null undefined NaN empty string ("") 0 false !! operator in node js This converts a value to a boolean and  ensures a boolean type . "foo" = "foo" ! "foo" = false !! "foo" = true Truth Table for javascript '' == '0' // false 0 == '' // true 0 == '0' // true false == 'false' // false false == '0' // true false == undefined // false false == null // false null == undefined // true " \t\r\n" == 0 // true NaN === NaN //false !! NaN === !! NaN //true