How to encrypt and decrypt Data using node.js

Encryption and Decryption are basically used for security purposes. We convert our actual data in some other form using some algorithms sha, RSA, etc during encryption. Vice versa we convert our encrypted data into actual forum during decryption.

In Node.js for Encryption and Decryption, we use crypto
package.

During Encryption and, Decryption we use security keys to make our encryption more strong.

For Encryption and, Decryption, we also used term encoding and decoding. During encryption, we encode our data and during decryption, we decode our data. 

Now we will write code for encrypting our data then after we will write code for decrypting our data.

But before that at first, we will declare our security keys that we are using for encryption and decryption.


// Declare package
var crypto = require('crypto');
// Declareing secret_key
let secret_key = 'encrypton_decryption';
// Declare secret_iv
let secret_iv = 'encrypton_decryption_iv';
// Declare encryption method
let encrypt_method = "AES-256-CBC";

Then after we will write code for encrypting our data as shown below.


const encryptData = async function (data) {
  let key = crypto.createHash('sha256').update(secret_key).digest('hex').substr(0, 32);
  let iv = crypto.createHash('sha256').update(secret_iv).digest('hex').substr(0, 16);
  let cipher = crypto.createCipheriv(encrypt_method, key, iv);
  let encrypted = cipher.update(data, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  return Buffer.from(Buffer.from(encrypted).toString('utf8')).toString('base64');
}

For calling this function we write these lines of code


let hw = encryptData("hello");
console.log(hw);

OutPut:
encrypt data
Now for decryption of our data, we will write these lines of code


const decryptData = async function (data) {
  let key = crypto.createHash('sha256', secret_key).update(secret_key).digest('hex').substr(0, 32);
  let iv = crypto.createHash('sha256', secret_key).update(secret_iv).digest('hex').substr(0, 16);
  var decipher = crypto.createDecipheriv(encrypt_method, key, iv);
  var dec = decipher.update(Buffer.from(data, 'base64').toString('ascii'), 'base64', 'utf8');
  dec += decipher.final('utf8');
  return Buffer.from(dec).toString('utf8');
}

And during calling decryptData function we will pass encrypted data that has been obtained from encryptData function as shown below


let decryphw = decryptData('SEJFL0VVYy83SGcwc1prZFZST3A2Zz09');
console.log(decryphw);

OutPut:

How to use Sequelize in Node.js

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. Its features are solid transaction support, relations, eager and lazy loading, read replication, and many more.

Here we explaining an example of a Database connection with MySQL using Squeeze.

Features of Sequelize:

  • Sequelize is a third-party package to be precise its an Object-Relational Mapping Library(ORM).
  • Standardization ORMs usually have a single schema definition in the code. This makes it very clear what the schema is, and very simple to change it.
  • No need to learn SQL – Queries are written in plain JavaScript. So there is no need to learn SOL.

Setting up a Node.js app:

Start Node.js app using the following command:


// initialise npm
npm init

Installation of Required packages:

Sequelize needs the MySql module installed in your project. if you have not installed MySql module then make sure before installing Sequelize you need to install MySql2 module. You need to install this module by using the following command.


// install mysql2
npm install mysql2

After installing the MySql2 module, we have to install Sequelize module to install this module by using the following command.


// install sequelize
npm install sequelize

Requiring module:

For including sequelize in our application we have to add these few lines


// include sequelize
const sequelize = require('sequelize');

For this application, we are creating two files

index.js

databaseConnection.js

databaseConnection.js : explain data onnection using sequelize


//include sequelize
const sequelize = require('sequelize');
// create new object for Database connection
const Sequelize = new sequelize(
    'sequelize_database_db',
    'root',
    'root',
    { 
        host: "localhost",
        dialect: "mysql"
    })

// export module

module.exports = Sequelize;

index.js : calling database connection script and run application


// import database connection module 
const Sequelize = require('./databaseConnection');
// sequelize db Connection ...
Sequelize
    .authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

Run application : Open terminal and run command


// Run app 
node index.js

OutPut:
sequelize dbconnection

you can download project from here.

download from git

Get Latest CSV file from Folder using Node.js

getLatestFile.js



/***
 * Read lestest file property 
 * 
 */

const fs = require('fs')
async function getLatestFile() {
    const dirPath = '/home/dheeraj/Documents/BlogPost/Downloads';
    let dirCont = fs.readdirSync(dirPath);
    let files = dirCont.filter(function (elm) { return elm.match(/.*\.(csv)/ig); });
    for (let fileP = 0; fileP < files.length; fileP++) {
        let filsStats = fs.statSync(dirPath + "/" + files[fileP]);
        if (new Date(filsStats['birthtime']).getDate() === new Date().getDate() &&
            new Date(filsStats['birthtime']).getMonth() === new Date().getMonth() &&
            new Date(filsStats['birthtime']).getFullYear() === new Date().getFullYear() &&
            new Date(filsStats['birthtime']).getHours() === new Date().getHours() //&& 
        ) {
            return {
                fileName: files[fileP],
                fileLocation: dirPath + "/" + files[fileP]
            };
        }
    }
    return {
        fileName: 'orderFailed.png',
        fileLocation: dirPath + "/" + 'orderFailed.png'
    };
}

Generate test case
getLatestFile.test.js


const {getLatestFile} = require('./getLatestFile')

async function getLatest (){
    let latest = await getLatestFile();
     console.log(latest);
}

getLatest();

OutPut:

Download Code From git Repo

Regex with JavaScript Part 3

Match WhiteSpaces

During searching or matching a string. We come across a situation where we need to match spaces in String literals.

For matching spaces in String literals, we use \s  which is a lowercase s.

Example:



/**
* Checking for WhiteSpaces
*/

let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
let spaceRegex=/\s/g;
console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Match Non-Whitespace Characters

Previously we had seen for searching white spaces using /s which lowercase s.

Here we are looking for searching Non-Whitespace and that can be done using /S , yes using upperCase s.

Example:



/**
 * Checking for WhiteSpaces
 */

 let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
 let spaceRegex=/\s/g;
 console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Specify Upper and Lower Number of Matches

We can specify the lower and upper number of patterns with quantity specifiers.

Quantity specifiers are used within curly brackets ({ and }).

Example:



/**
 * specify upper and lower number of match
 */

let myString ="mmmmmmmk";
let mySecondString ="mk";
// match word "mmmmmmmk" only it has minimum 2 and maximum 4 'm'
let myRegex=/m{2,4}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Specify Only the Lower Number of Matches
Passed

Sometimes we need to match only a lower number of matches.

So To specify a lower number of matches keep the lower number of matches followed by comma in curly bracket ( { n, } ).

where n is a lower number.

Example:



/**
* specify lower number of match
*/

let myString ="pinnnnnnnnnnk";
let mySecondString ="pinnk";
// match word "pinnk" only it has four or more letter of n
let myRegex=/pin{4,}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test((mySecondString)));

OutPut:

Specify Exact Number of Matches

Sometimes we need to specify an exact number of matches.

To specify an exact number of pattern just add that number in curly bracket.

Example:


/**
* specify exact match
*
*/

let myString = "apple";
let mySecondString ="aple";
//p should be appear two times
let myRegex = /ap{2}l/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Check for All or None

Sometimes we are not sure about the pattern that we are searching for. 

In that case, we use ‘?’ i.e question mark which check for zero or one of the preceding element.

In other words, we can also say that the previous character is optional i.e if that exists then fine and if not then also no problem.

Example:



/**
*
* Check for All or None
*/


let american ="favorite";
let british ="favourite";
let regexPattern = /favou?rite/;

//In this example 'u' is optional
console.log(regexPattern.test(american));
console.log(regexPattern.test(british));

OutPut:

Positive and Negative Lookahead

Lookaheads are patterns in Javascript that tells to Javascript to look-ahead in your string to check for pattern further long.

It can be helpful during searching multiple patterns on the same string.

There are two kinds of Lookaheads :

  • Positive lookahead
  • Negative lookahead

Positive lookahead :

– Look to make sure the element in the search pattern is there, but won’t actually match it.

– Positive Lookahead is used as (?= …)

– Where  the ... is the required part that is not matched.

Negative lookahead :

– Look to make sure the element in the search pattern is not there.

– Negative lookahead is used as (?!...) 

– where the ... is the pattern that you do not want to be there.

Example:



/**
 * lookahead 
 * 
 */

 let myPassword = "ohMyGod123";
 let mySecondPassword ="ohmyGod";
 // regex for a string greater than 5 character long and don't begin with number and have two consequitive numbers
 let myRegex = /^(?=\w{6}(?=\D+\d{2}))/;
 console.log(myRegex.test(myPassword));
 console.log(myRegex.test(mySecondPassword));

OutPut:

Check For Mixed Grouping of Characters Passed

Sometimes we need to match a group of Characters using regular expression.
We can achieve that using () i.e parenthesis.

Example :



/**
*  Mixed grouping Characters
*/

let myString = "laptop";
// check for multiple group of characters
let myRegex = /(lap|Desk)top/;
console.log(myRegex.test(myString));

OutPut:

Reuse Patterns Using Capture Groups

Some patterns are multiple times in a string. Then it is wastage of time to write the pattern multiple times for searching in a string.

Example:



/**
* Reuse patterns using capture Groups
*
*/

let myString ="mummy mummy mummy";
let myRegex = /(\w+)\s\1/;

console.log(myRegex.test(myString));

console.log(myString.match(myRegex));

OutPut:

Use Capture Groups to Search and Replace

We can search and after that replace in string using .replace().

.replace() contains two parameters :

  • First parameter the string that we are searching for
  • Second parameter the string from which we want to replace.

Example:



/**
* Capture group for search andd replace
*/

let myString= "Baba Black Sheep";
// replace Baba Black sheep with Sheep Black Baba
let myRegex = /(\w+)\s(\w+)\s(\w+)/
let myReplacementString= '$3 $2 $1';
console.log(myString.replace(myRegex,myReplacementString));

OutPut:

Remove Whitespace from Start and End

Sometimes we come across the problem that some string contains unwanted whitespaces and that we need to remove these whitespaces from our string.
For removing start and end whitespaces from a string from we use .trim()
method.

Example:



/***
* removing whitespace from string using .trim()
*/

let hello = "   Hello, World!  ";

let result = hello.trim();
console.log(result);

OutPut:

Stylish JavaScript with es6

ECMAScript is the Standard version of Javascript with a goal of unifying language specifications and features. All significant Browsers and JavaScript compilers support ECMAScript.

In this post, we will cover some major key points of es6 

Variable with es6
Objects with es6
Function with es6

Variable with es6

Variable Declaration with es6

In JavaScript for declaring a variable var keyword is used.

Example :



# comment line 
var someVariable ="Some thing";
console.log(someVariable)

Output:

javascript variable Decleration

But in case of es6 we have three keywords for Declaring a variable these are let, var , const.

Then question arises

Why es6 contains three keywords for declaring a variable?

 Or

What is the problem with ‘var’ keyword so that ECMAScript was needed to introduce two more keywords?

The biggest problem with var keyword is that we can overwrite a variable declaration without any error.

Example :



/**
* Overwrite a Variable
*/

var someVariable="Something";
var someVariable="Nothing";
console.log(someVariable);

Output:

overwrite variable with Javascript

But in case of Declaration with let keyword, we can’t do so.

Example :



/**
* Overwrite a variable with let keyword
*/

let someVariable="Something";
let someVariable="Nothing"; // throw error
console.log(someVariable);

OutPut:

Similarly, const keyword is used for declaring a constant variable inside the complete script.
Example:



/**
* Calculate Area of Circle
*/
Types of Joins
Const PI =3.14
let radius=12m;
console.log("Area of Circle is :: ",(PI*(radius*radius)));

Objects with es6

Objects are similar to Arrays. But in Objects, we can access and modify data with the help of their properties.
But in the case of Arrays, we use indexes to access and modify data.

Objects are Userful for Storing data

Data in a structural way looks like real-world data.



/**
  * Declaring an Object
*/


var book={
  "name":"IKIGAI",
   "author":"Hector Garcia & Francesc Meralies" ,
   "publication":"Penguin"
}

In the above example, Book is an Object and name, author and publication are its properties.

How to access JavaScript Objects?

For accessing JavaScript Object (Same for es6) we can follow these approaches :

  • Accessing JavaScript Object Properties using DotNotation
  • Accessing JavaScript Properties with Bracket Notation
  • Accessing JavaScript Properties with Variables
Accessing JavaScript Object Properties using DotNotation


/**
  *Accessing Javascript Object using DotNotation 
*/

var book={
  "name":"IKIGAI",
   "author":"Hector Garcia & Francesc Meralies" ,
   "publication":"Penguin"
}
//accesing book name
console.log(book.name);
//accessing book author
console.log(book.author);
//accessing book publication
console.log(book.publication);

Output:

Accessing JavaScript Properties with Bracket Notation

We can access the above values also using Bracket Notation.



/**
  *Accessing Javascript Object using BracketNotation 
*/

var book={
  "name":"IKIGAI",
   "author":"Hector Garcia & Francesc Meralies" ,
   "publication":"Penguin"
}
//accesing book name
 console.log(book["name"]);
//accessing book author
console.log(book["author"]);
//accessing book publication
 console.log(book["publication"])

Output:

Accessing JavaScript Properties with Variables

We can also access JavaScript Objet with help of Variables as shown below example. Again in case of Accessing JavaScript Properties with Variables, we are going to use Bracket Notation.



/**
  *Accessing JavaScript Properties with Variables
*/

var favourite = {
      game: "Cricket",  food: "Litti",  movieSeries: "X-man"
  };
  var myFavourite = "food";  //Declaring a new variable
  var myFavouriteFood = favourite[myFavourite];
  console.log("My favourite Food ::",myFavouriteFood); 

OutPut:

In this example, Object favorite contains a set of key-value pairs i.e properties and we will access properties of favorite objects on the basis of a variable myFavorite.

Function with es6

For Declaring a function in Javascript there are several ways.
Simplest way
Simplest way for declaring a function in Javascript is
Syntax:



/**
  *function declaration
*/


function function_name(){

 //function body 
}

Example: Add Two Numbers in JavaScript



/**
  * funtion decalartion
  */
 
 function addNum(a,b){
 
   return console.log("Addition of Two Numbers :: ",a+b);
 
 }
//calling function
 
 addNum(5,6);

OutPut:

Anonymous Function

A function which doesn’t contain its name is known as Anonymous function.
We can perform the same operation using the Anonymous function.
Syntax :



function (){
    //function body 
}

Example:



/**
  * Anonymous function declaration
  */

 
 var addNum =function (a,b){
   
   return console.log("Addition of Two Numbers :: ",a+b);
 }
//calling function
 addNum(5,6);

OutPut:

Arrow function

es6 introduces a new way for function declaration known as Arrow function.
Syntax:


()=>{

  //function body

}

Example:



/**
  * arrow funtion decalartion
  */

 let  addNum = (a,b) =>{
   return console.log("Addition of Two Numbers :: ",a+b);
 }
//call function
addNum(5,6);

OutPut: