Home Blog Page 4

NodeJS Allow whitelisted IP to use Express Server

White Listing IP in NodeJS Express Server
White Listing IP in NodeJS Express Server

Node.JS as you know is single threaded, asynchronous, event-driven architecture, Is so popular JavaScript JavaScript runtime environment for building high performance web application or back-end application like express server or Rest API’s.

You are here to know how can I increase the security level of my NodeJS express server by whitelisting IP to use our node server.

In this NodeJS article let’s explore how to enhance security of our NodeJS Express by adding middleware to check the whitelisted IP and allow only specific Client IP address to access our server.

Video Tutorial

The code complete source code with explanation is as below

Allow Only one specific IP


const express = require('express')

const app = express();

const checkIpAccess = (req,res,next)=>{
    const ALLOWEDID = "";
    const CLIENTIP = req.ip;



  res.send(`ALLOWED ACCESS  ${req.ip}`);

  console.log("Server Running at port 3000");

Whitelisting multiple IP’s in NodeJS

const express = require('express');
const app = express();

const checkIpAccess = (req, res, next) => {
    const ALLOWEDIPS = ["", "", ""];
    const CLIENTIP = req.ip;

    if (ALLOWEDIPS.includes(CLIENTIP) || ALLOWEDIPS.includes("::ffff:" + CLIENTIP)) {
    } else {


app.get('/', (req, res) => {
    res.send(`ALLOWED ACCESS  ${req.ip}`);

app.listen(3000, () => {
    console.log("Server Running at port 3000");

Understanding the above code

The above code make use of ExpressJS to run a NodeJS server, which makes use of middleware function checkIpAccess thta is responsible to check the client request IP address if that IP exist in our allowed whitelisted IP list then grant the user to use our nodejs server else return a status error 403 that is forbidden.

Benefits of IP Whitelisting

Implementing IP whitelisting in your Node.js Express server offers several security advantages:

  1. Access Control: Only requests originating from the specified IP address are permitted, providing a level of access control.
  2. Reduced Attack Surface: By restricting access to a single IP, you minimize the potential attack surface, making it more challenging for unauthorized users to interact with your server.
  3. Enhanced Security: IP whitelisting is an additional layer of security, complementing other security measures you may have in place.

JavaScript: Solutions to 5 Essential Interview Questions

javascript interview questions
JS questions

In today’s world JavaScript versatile & been widely-used as a programming language that plays an important role in modern web development. Being a JavaScript developer, It’s very important to understand the language’s fundamentals and also adept solving real-world problems. In JS job interviews, JavaScript Interview Questions is been often asked from basic syntax to advanced concepts.

In this article, We will dive into 11 JavaScript questions that are commonly asked in interviews. Each question will be explained in detailed with solution, complete with source code examples where required.

If are you getting prepared for you next job interview or simple learning to enhance your JS skill, this article will have practical solution with code example for better understanding.

5 Interview Questions for JavaScript Job preparation

1. Implement a function that serializes a JavaScript value into a JSON string.

In JS we have a In-Built method i.e. JSON.stringify() using which we can easily convert javascript object or value into JSON string.

function serializeToJsonString(value) {
  try {
    const jsonString = JSON.stringify(value);
    return jsonString;
  } catch (error) {
    console.error('Serialization error:', error);
    return null;

// Example JS Object:
const data = {
  name: 'John Doe',
  age: 30,
  city: 'Example City'

const jsonString = serializeToJsonString(data);

In Above example we have a function which accept a data object and return a jsonString.

2. Write a JS function which performs a deep copy of a value, and also handles circular references.

Before going in above question let’s understand what is shallow copy and deep copy.

Shallow and Deep copy are concept in JS which is been used while working with object or array in javascipt:

Shallow Copy in JavaScript:

In below source code, I am creating a copy of originalObject using Assignment Operator (=) and then the copyed object shallowCopy is modified…

const originalObject = { a: 1, b: { c: 2 } };

// Shallow Copy using assignment operator
const shallowCopy =  originalObject;

console.log('Original Object: Before', originalObject);
console.log('Shallow Copy: Before', shallowCopy);

// Modifying the Shallow Copy
shallowCopy.b.c = 99;

console.log('Original Object:', originalObject);
console.log('Shallow Copy:', shallowCopy);

In Shallow Copy when you create a new object using originalObject, actually the shallowCopy points to same address to which originalObject is, Now when we modify shallowCopy the modification is made at address level, due to which originalObject will also get altered.

Original Object: Before { a: 1, b: { c: 2 } }
Shallow Copy: Before { a: 1, b: { c: 2 } }
Original Object: { a: 1, b: { c: 99 } }
Shallow Copy: { a: 1, b: { c: 99 } }

Deep Copy in JavaScript:

In below example, JSON.stringify() is used to serialize the original object into a JSON string, and then JSON.parse() is used to parse it back into a new object.

Doing this will create a deep copy, making sure that original data is not modified when copy is modified.

// Original Object
const originalObject = { a: 1, b: { c: 2 } };

// Deep Copy using JSON.stringify() and JSON.parse()
const deepCopy = JSON.parse(JSON.stringify(originalObject));

// Modifying the Deep Copy
deepCopy.b.c = 99;

console.log('Original Object:', originalObject);
console.log('Deep Copy:', deepCopy);

Now, Let’s performs a deep copy of a value, and also handles circular references

Note: We are using NodeJS circular-json library to handle circular references with deep clone.

const CircularJSON = require('circular-json');

function deepCopyWithCircularHandling(obj) {
  try {
    const jsonString = CircularJSON.stringify(obj);
    const copy = CircularJSON.parse(jsonString);
    return copy;
  } catch (error) {
    console.error('Deep copy error:', error);
    return null;

// Example usage:
const originalObject = {
  prop1: 'value1',
  prop2: {
    prop3: 'value3'

originalObject.circularReference = originalObject;

const copiedObject = deepCopyWithCircularHandling(originalObject);

In this example, the circular-json library is used to stringify and parse the object with circular references.

3. Create a Function in JS then accepts any numbers of arguments and returned memorized version

To Implement Memorization of data or we can say it as creating a cache of the data returned by a javascript function can be achieved by using caching technique.
Below Code example uses simple cache object.

function memoize(func) {
  const cache = {};

  return function (...args) {
    const key = JSON.stringify(args);

    if (cache[key]) {
      console.log('Fetching from cache');
      return cache[key];
    } else {
      console.log('Calculating result');
      const result = func(...args);
      cache[key] = result;
      return result;

// Example usage:
const sum = memoize((...args) => args.reduce((acc, val) => acc + val, 0));

console.log(sum(1, 2, 3)); // Calculating result
console.log(sum(1, 2, 3)); // Fetching from cache

4. How do you stop a setInterval() function

We can easily stop setInterval() function of javascript, by making use of clearInterval(intervalId) method. The clearInterval method accept a parameter i.e. the ID of setInterval() method by which be can stop further executions of setInterval() func.

var i = 0;
const intervalId = setInterval(()=>{
    console.log("i=> ",i)

The above code will stop execution of setInterval() when i value is 5.

5. How to Merge Two Object in JavaScript

There are many ways to merge or cancat two object into one, i.e. by using spread operator (...) or by uisng Object.assign() method.

The below example to merge two object using spread operator (...).

function mergeObjects(obj1, obj2) {
  return { ...obj1, ...obj2 };

// Example usage:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 4 };

const mergedObject = mergeObjects(obj1, obj2);
console.log(mergedObject); // result: { a: 1, b: 2, c: 4 }

The below example to merge two object using Object.assign() method.

function mergeObjects(obj1, obj2) {
  // Create a new object and use Object.assign to merge obj1 and obj2
  const mergedObject = Object.assign({}, obj1, obj2);
  return mergedObject;

// Example usage:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };

const mergedObject = mergeObjects(obj1, obj2);
console.log(mergedObject); // result: { a: 1, b: 3, c: 4 }

JavaScript for…in Loop: Iterating an object

for…in object javascript

Hi Guy’s Welcome to Proto Coders Point, In this JS Article let’s under about looking in javascript using for…in loop.

for…in object javascript -How to iterate object in javascript

In Javascript, for…in loop statement is commonly used to iterate object over it’s properties also known a key of an object. This for…in loop is only recommended to used with object not with any array as the behavior might changed during iteration.

Syntax of for…in object loop

for (var key in object) {
    // code to be executed for each property/key

for…in loop example to iterate object to access it’s properties

const person = {
  firstName: "Rajat",
  lastName: "Palankar",
  age: 20,
  email: "contact@protocoderspoint.com"

for (var key in person) {
  console.log(key + ": " + person[key]);


In above code we have an object by name person & I want to iterate it so for that I am using for…in loop to iterate the object over it’s properties.

Each loop it iterate has it’s key property and using that key we can access it’s corresponding value. The output is below:

firstName: Rajat
lastName: Palankar
age: 20
email: contact@protocoderspoint.com

Note: Use for…in loop use only on object, as it misbehave which used with arrays. For iterating an arrays it’s better to use for…of loop or forEach loop.

Similar Articles

convert array into collection

15 useful Javascript Snippets code

What Are DNS Records & What are the kinds of DNS records?

DNS Record

Simply typing a website’s address into a browser’s address bar will not bring up the desired page. Without it, we’d all have to commit long, difficult-to-remember IP numbers to memory in favor of more human-friendly domain names.

What are DNS records, and what kinds of DNS records are discussed in more detail below:

What is a DNS record?

Zone files, or DNS records, are stored in authoritative DNS servers and include information about a domain, such as its IP address and how to respond to queries for that domain. These are text files written in DNS syntax and include relevant information. DNS syntax is just a string of characters that serve as instructions for the DNS server. TTL, “time-to-live,” is included in every DNS record and specifies how often the DNS server will update the record.

A DNS record set is similar to a Yelp page for a company. All the pertinent details about a specific business, such as its address, operating hours, types of services it provides, etc., are included in that listing. A minimum number of DNS records must be present on every domain before it can be used to visit a website, and many more can be included for convenience.

What are the kinds of DNS records?

You may find crucial details about a domain or hostname in DNS records. Current domain IP addresses are stored in these entries.

Also, the authoritative DNS server uses text files called zone files to hold DNS records. DNS record files include text interpreted as a string by the DNS server and containing special directives.

Forms of Domain Name System Records

Below are the five most common kinds of DNS records:

  • A record
  • AAAA record
  • CNAME record
  • Nameserver (NS) record
  • Mail exchange (MX) record

Each of the categories, as mentioned earlier, serves a unique purpose. Therefore, let’s take a closer look at the various DNS record types.

1. A Record

DNS records come in various types, but none are more crucial than the A record. When you hear “A record,” you’re attending the phrase “address.” The IP address associated with a specific hostname or domain is displayed in an A record. A record is mainly used for IPv4 address lookup. An A record is required for a web browser to access a website by that domain name. Due to this, we may visit websites online without needing to know their IP addresses.

The A record is also utilized in a black hole list based on the domain name system (DNSBL). In this instance, spam is prevented by modifying the A record to reject messages from specific senders.

2. AAAA Record

Similar to how A records reveal a domain’s IPv4 address, AAAA records indicate the IPv6 address of a host. It’s important to note that this particular DNS record type is unique because it only resolves to IPv6 addresses.  IPv6 is superior to IPv4 because it provides more IP addresses. IPv6 resolves the problem of a lack of available IP addresses.

For DNS resolution, the AAAA record is preferable to the A record since it employs IPv6, which is more secure than IPv4. Also, the possibility for AAAA records is excellent because the Internet is expanding, and we’re running out of IPv4 addresses. Domain names require AAAA records to be resolved to use the more modern IPv6 protocol.

3. CNAME Record

Canonical Name (CNAME) records redirect traffic from one domain to another. However, the alias in a CNAME record does not resolve to a specific IP address. To clarify, the canonical name is the domain name that the alias redirects to.

4. NS record

The primary DNS server for a domain is identified in its nameserver (NS) record. In other words, the NS record indicates to internet programs like web browsers where they may locate a domain’s IP address. Typically, a domain will have many nameservers listed. Those who have purchased web hosting or created an essential website have likely been sent an email containing their nameserver information. Nameservers are the intermediaries between your domain and the server hosting your site. Other domain name server records, such as the A and MX records, are stored on the nameserver.

5. MX Record

A DNS record known as a mail exchange (MX) record specifies an email server that will receive messages addressed to a domain. So, an MX record allows email to be routed to a particular server.

Multiple MX records can exist for the same domain. That paves the way for the availability of emergency email servers.

How to perform the DNS Lookup?

Performing the DNS record lookup is simple and easy. You can use an online tool or perform that using a command.

Windows Command Prompt:

To perform a DNS lookup in Windows using the Command Prompt, you can use the `nslookup` or `ping` command. Here’s how to use both methods:

1. Using nslookup:

   – Open the Command Prompt by searching for “cmd” in the Windows Start menu.

   – Type the following command and replace “example.com” with the domain or hostname you want to look up:

   nslookup example.com

   – Press Enter. This will provide you with DNS information, including the IP addresses associated with the domain.

2. Using ping:

   – You can also use the `ping` command to perform a DNS lookup. Just type:

   ping example.com

   – Press Enter, and it will display the IP address of the domain along with some ping statistics.

Linux/Unix/macOS Terminal:

To perform a DNS lookup in Linux, Unix, or macOS, you can use the `nslookup`, `host`, or `dig` commands. Here’s how to use each of them:

1. Using nslookup:

   – Open your terminal.

   – Type the following command and replace “example.com” with the domain or hostname you want to look up:

   nslookup example.com

   – Press Enter.

2. Using host:

   – Open your terminal.

   – Type the following command and replace “example.com” with the domain or hostname you want to look up:

   host example.com

   – Press Enter.

3. Using dig:

   – The `dig` command provides more detailed DNS information. Open your terminal and type:

   dig example.com

   – Press Enter.

The output of these commands will provide you with DNS information, including the IP addresses associated with the domain. Choose the command that suits your needs and your specific operating system.

Merging Two Maps in Dart – Flutter

Merging Two Maps in Dart
How to merge two map in flutter

Hi Guy’s In this Tutorial, Let’s checkout how to merge 2 maps into one in flutter dart.

If you are working with dart programming language you might have come with situation when you want to combine 2 maps objects. For Example let’s say, a Map that stores name of a user, his phone number and email address and there is another map that contain that user house address, his family details etc. In such scenerio merging 2 maps in single map is benefit because all the information about user is one one data itself.

In this dart article, let’s walk through differents ways of join 2 maps in one.

1. Using (…) spread operator

2. Using addAll() method.

3. Using putIfAbsent() method.

Merging 2 Maps Object using spread operator

This is one way by which we can easily join/combine 2 map in one i.e using spread operator (…). By using thi approach two collection of maps are merged into one collection.


// main.dart

void main() {
  Map<String, int> map1 = {'a': 1, 'b': 2};
  Map<String, int> map2 = {'c': 3, 'd': 4, 'c': 5};

  Map<String, int> mergedMap = {...map1, ...map2};



{a: 1, b: 2, c: 5, d: 4}

Note: Here if there are duplicate keys present in the maps that you are merging then in such case the value of second map will be overwriten the value of first map. In above example as you can see key c value is 3 and same in map2 key c value is 5 so final result we get is c:5 that is from map2.

Merge 2 maps using addAll() method

Their is another way by which we can merge map in dart that is by using addAll() method, What this function does is it simply copy all the key & value from map 2 to map 1. let’s understand with an example


void main() {
  Map<String, int> map1 = {'a': 1, 'b': 2,'e':1};
  Map<String, int> map2 = {'c': 3, 'd': 4, 'e': 5};

  // merge map2 into map1



{a: 1, b: 2, e: 5, c: 3, d: 4}

addAll() method copy all the key & value from map 2 and add it into map 1, That means addAll() method will directly modify the first map.

Merge 2 map using putifAbsent() method

As we saw in above ways, The value of a key is modified if same key is present. To solve this problem we can make use of putifAbsent() method. Let’s understand with an example

// main.dart
void main() {
  Map<String, String> map1 = {'firstname': "Rajat", 'lastname': "Palankar"};
  Map<String, String> map2 = {'address': "India", 'firstname': "NameChanged", 'website': "protocoderspoint.com"};

  map2.forEach((key, value) {
    map1.putIfAbsent(key, () => value);


{firstname: Rajat, lastname: Palankar, address: India, website: protocoderspoint.com}

This approach to join or merge 2 map is useful then you don’t want to keep duplicate data. In above example I am iterating map2 using forEach loop then checking is same key present in map 1, if not then add map 2 key and value in map 1 using putIfAbsent() and ignore it.

Sorting Arrays in Java: How to use Arrays.sort() Method

Arrays.sort() Java
sorting in java

Hi Guy’s, Java being the most popular programming language comes with an efficient & versatile sorting technique. In this Article let’s dive into a sorting method i.e. Arrays.sort(), This sorting technique enable the java developer with super power to sort an Array effortlessly and arranging the elements in ascending or descending order as per the requirement.

Arrays.sort() java

Arrays.sort() is robust method using which a developer can sort arrays of primitive data types or an objects.



Sorting array of object in java

To sort an array of objects, we need a custom comparator or ensure that the array implement the comparable interface.


Code Example to use Arrays.sort() method

1. Sorting an array of integers

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // Sorting an array of integers
        int[] intArray = {5, 2, 9, 1, 5, 6};
        System.out.println("Original integer array: " + Arrays.toString(intArray));
        System.out.println("Sorted integer array: " + Arrays.toString(intArray));
Original integer array: [5, 2, 9, 1, 5, 6]
Sorted integer array: [1, 2, 5, 5, 6, 9]

2. Sorting Array of strings

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // Sorting an array of strings
        String[] stringArray = {"banana", "apple", "cherry", "date", "elderberry"};
        System.out.println("Original string array: " + Arrays.toString(stringArray));
        System.out.println("Sorted string array: " + Arrays.toString(stringArray));
Original string array: [banana, apple, cherry, date, elderberry]
Sorted string array: [apple, banana, cherry, date, elderberry]

3. Sorting Array of Object

In below sorting an array of object, I am sorting the object by name.

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // Sorting an array of custom objects
        Person[] personArray = {new Person("John", 30), new Person("Alice", 25), new Person("Bob", 35)};
        System.out.println("Original Person array: " + Arrays.toString(personArray));

        Arrays.sort(personArray, (a, b) -> a.getName().compareTo(b.getName()));
        System.out.println("Sorted Person array by name: " + Arrays.toString(personArray));

   // class 
    static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;

        public String getName() {
            return name;

        public String toString() {
            return "Person{name='" + name + "', age=" + age + "}";
Original Person array: [Person{name='John', age=30}, Person{name='Alice', age=25}, Person{name='Bob', age=35}]
Sorted Person array by name: [Person{name='Alice', age=25}, Person{name='Bob', age=35}, Person{name='John', age=30}]

The above code example is to demonstrates how to use ‘Arrays.sort()’ method for aorting datatype like integersm string and a class object in java.