Node JS experienced interview questions


Is Node.js Single-threaded? Why it is required?

Yes, Node Js is single threaded to perform asynchronous processing.
All Node JS applications uses “Single Threaded Event Loop Model” architecture to handle multiple concurrent clients. Doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

What are events in Node Js?

An event is an action or occurrence recognized by software/app that is handled by event handler by writing a code that will be executed when the event fired.
Mouse move, Click, file copied or deleted are some examples of events.
In Node Js there are two types of events.
1)System Events: The event that comes from the C++ side.
2)Custom Events: Custom events are user-defined events.

What is an event loop in Node Js?

In Node Js processes are single threaded, to supports concurrency it uses events and callbacks. An event loop is a mechanism that allows Node.js to perform non-blocking I/O operations.

What is Express JS?

Express JS is an application framework which is light-weighted node JS. A number of flexible, useful and important features are provided by this JavaScript framework for the development of mobile as well as web applications with the help of node JS.

List some features of Express JS.

Some of the main features of Express JS are listed below: –

  • It is used for setting up middlewares so as to provide a response to the HTTP or RESTful requests.
  • With the help of express JS, the routing table can be defined for performing various HTTP operations.
  • It is also used for dynamically rendering HTML pages which are based on passing arguments to the templates.
  • It provides each and every feature which is provided by core Node JS.
  • The performance of Express JS is adequate due to the presence of a thin layer prepared by the Express JS.
  • It is used for organizing the web applications into the MVC architecture.
  • Everything from routes to rendering view and performing HTTP requests can be managed by Express JS.

Why we need to use Express.js in a node application?

Below are the few reasons why to use Express with Node.js

  • Express js is built on top of Node.js. It is the perfect framework for ultra-fast Input / Output.
  • Cross Platform
  • Support MVC Design pattern
  • Support of NoSQL databases out of the box.
  • Multiple templating engine support i.e. Jade or EJS which reduces the amount of HTML code you have to write for a page.
  • Support Middleware, basic web-server creation, and easy routing tools.

What are the differences between readFile and createReadStream in Node.js?

  • readFile load the whole file which you had marked to read whereas createReadStream reads the complete file in the parts of the size you have declared.
  • The client will receive the data faster in the case of createReadStream in contrast with readFile.
  • In readFile, a file will first completely read by memory and then transfers to a client but in later option, a file will be read by memory in a part which is sent to clients and the process continue until all the parts finish.

Show example for asynchronously/blocking and asynchronously/non-blocking

Normally NodeJs reads the content of a file in non-blocking, asynchronous way. Node Js uses its fs core API to deal with files. The easiest way to read the entire content of a file in nodeJs is with fs.readFile method. Below is sample code to read a file in NodeJs asynchronously and synchronously.

Reading a file in node asynchronously/ non-blocking

var fs = require('fs');  
fs.readFile('DATA', 'utf8', function(err, contents) { console.log(contents);
});
console.log('after calling readFile');

Reading a file in node asynchronously/blocking

var fs = require('fs'); 
var contents = fs.readFileSync('DATA', 'utf8'); console.log(contents);

What are Streams? List types of streams available in Node Js?

Streams are special types of objects in Node that allow us to read data from a source or write data to a destination continuously. There are 4 types of streams available in Node Js, they are

  • Readable − For reading operation.
  • Writable − For writing operation.
  • Duplex − Used for both read and write operation.
  • Transform − A type of duplex stream where the output is computed based on the input.

How to generate unique UUIDs/ guid in Node Js

Use node-uuid package to generate unique UUIDs/ guid in Node Js. Below code demonstrates how to generate it.

var uuid = require('node-uuid'); 
// Generate a v1 (time-based) id
uuid.v1();
// Generate a v4 (random) id
uuid.v4();

Rewrite the code sample without try/catch block:

Source: medium.com

Consider the code:

async function check(req, res) {
  try {
    const a = await someOtherFunction();
    const b = await somethingElseFunction();
    res.send("result")
  } catch (error) {
    res.send(error.stack);
  }
}

Rewrite the code sample without try/catch block.

Answer:

async function getData(){
  const a = await someFunction().catch((error)=>console.log(error));
  const b = await someOtherFunction().catch((error)=>console.log(error));
  if (a && b) console.log("some result")
}

or if you wish to know which specific function caused error:

async function loginController() {
  try {
    const a = await loginService().
    catch((error) => {
      throw new CustomErrorHandler({
        code: 101,
        message: "a failed",
        error: error
      })
    });
    const b = await someUtil().
    catch((error) => {
      throw new CustomErrorHandler({
        code: 102,
        message: "b failed",
        error: error
      })
    });
    //someoeeoe
    if (a && b) console.log("no one failed")
  } catch (error) {
    if (!(error instanceof CustomErrorHandler)) {
      console.log("gen error", error)
    }
  }
}

Advertisements
Posted in Nodejs, Others

How to convert a JKS Keystore to a PKCS12 (.p12) format


To convert a JKS (.jks) keystore to a PKCS12 (.p12) keystore, run the following command:

Note: This command is supported on JDK / JRE keytool versions 1.6 and greater.

keytool -importkeystore -srckeystore <jks_file_name.jks> -destkeystore <pk12_file_name.p12> -srcstoretype JKS -deststoretype PKCS12 -deststorepass <password>

To verify the content of .p12 (e.g. pk12_file_name.p12), run the following command:
keytool -list -v -keystore <“pk12_file_name.p12”> -storetype <password>

Tagged with: ,
Posted in JAVA

What is a WeakMap in ES6?


A WeakMap is just like a normal Map with a few key differences:

  1. a WeakMap can only contain objects as keys,
  2. a WeakMap is not iterable which means it can’t be looped and
  3. a WeakMap does not have a .clear() method.

Below example shows how to create a WeakMap, it just like you would a normal Map, except that you use the WeakMap constructor.

const book1 = { title: ‘book 1’, author: ‘author 1’ };
const book2 = { title: ‘book 2’, author: ‘author 2’};
const book3 = { title: ‘book 3’, author: ‘author 3’ };

const library = new WeakMap();
library.set(book1, true);
library.set(book2, false);
library.set(book3, true);

console.log(library);

Output:

WeakMap {Object {title: ‘book 1’, author: ‘author 1’ => true, Object {title: ‘book 2’, author: ‘author 2’} => false, Object {title: ‘book 3’, author: ‘author 3’} => true}

…but if you try to add something other than an object as a key, you’ll get an error!

library.set(‘book 4’, false);
Uncaught TypeError: Invalid value used as weak map key(…)

This is because WeakMap can only contain objects as keys. WeakMaps leverage garbage collection for easier use and maintainability.

Tagged with: , , , , , ,
Posted in ES6, JavaScript

ES6 Default Function Parameters


Unlike the defining the default values in JavaScript, ES6 has provided a flexibility to define the default values during the function definition time.  In regular Javascript, we define a variable with one value, override that value with in the function logic. Here is an example to define default values in ES6.

function greet(name = ‘Student’, greeting = ‘Welcome’) {
return `${greeting} ${name}!`;
}

greet(); // Welcome Student!
greet(‘Mallik’); // Welcome Mallik!
greet(‘Mallik’, ‘Hi’); // Hi Mallik!

Output of above function:

Welcome Student!
Welcome Mallik!
Hi Mallik!

To create a default parameter, you add an equal sign ( = ) and then whatever you want the parameter to default to if an argument is not provided. In the above example, both parameters have default values of strings, but they can be any JavaScript type!

Tagged with: , , , , , ,
Posted in ES6, JavaScript, Struts

Arrow Functions in ES6


ES6 introduces a new kind of function called arrow function. Arrow functions are very similar to regular functions in behavior, but are quite different syntactically. They will save developers time and simplify function scope. The following code takes a list of names and converts each one to uppercase using a regular function:

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map(function(name) {
return name.toUpperCase();
});

The code below does the same thing except instead of passing a regular function to the map() method, it passes an arrow function. Notice the arrow in the arrow function ( => ) in the code below:

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map(
name => name.toUpperCase()
);

The only change to the code above is the code inside the map() method. It takes a regular function and changes it to use an arrow function.

Another Example for Arrow Functions is below:

var multiply = (x, y) => x*y;

Arrow functions are always function expressions, their full name is “arrow function expressions”, so they can only be used where an expression is valid. This includes being:

  • stored in a variable,
  • passed as an argument to a function,
  • and stored in an object’s property.

If there are zero items in the list, then you need to wrap the list in parentheses:

// empty parameter list requires parentheses
const sayHi = () => console.log(‘Hello MallikTalksJava!’);
sayHi();

If there’s only one parameter in the list, then you can write it just like the example below.

name => `Hello ${name}!`

If there are multiple parameters in the list, then you can write it just like the example below.

const orderIceCream = (flower, color) => console.log(`Color of ${flower} flower is ${color}.`);
orderIceCream(‘Rose’, ‘Red’);

There are two types syntaxes for arrow functions:
1. concise body syntax : All the examples mentioned above are comes under this category.
2. block body syntax : If you need more than just a single line of code in your arrow function’s body, then you can use the “block body syntax”.

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map( name => {
name = name.toUpperCase();
return `${name} has ${name.length} characters in their name`;
});

Advantages of Arrow functions:

  • The syntax is a lot shorter,
  • it’s easier to write and read short, single-line functions,
  • and they automatically return when using the concise body syntax!
Tagged with: , , , , , , , , ,
Posted in ES6, JavaScript

ES6 variable declaration – let and const


In standard Javascript, the only way to declare a variable in JavaScript was to use the keyword var.

But, in ES6 there are now two new ways to declare variables in JavaScript: let and constlet and const have some other interesting properties.

  • Variables declared with let can be reassigned, but can’t be redeclared in the same scope.
  • Variables declared with const must be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.

Below is the example to show how let and const is being used:

const CHARACTER_LIMIT = 255;
const posts = [
“Mallik”,
“talksjava “,
“.com”
];

// prints posts to the console
function displayPosts() {
for (let i = 0; i < posts.length; i++) {
console.log(posts[i].slice(0, CHARACTER_LIMIT));
}
}

displayPosts();

Output:

Mallik

talksjava

.com

The big question is when should you use let and const? The general rule of thumb is as follows:

  • use let when you plan to reassign new values to a variable, and
  • use const when you don’t plan on reassigning new values to a variable.

Since const is the strictest way to declare a variable,  you always declare variables with const because it’ll make your code easier to reason about since you know the identifiers won’t change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.

Tagged with: , , , , ,
Posted in ES6, JavaScript

Example Program to combine arrays in ES6


Here is one example of when the spread operator can be useful is when combining arrays.

If you’ve ever needed to combine multiple arrays, prior to the spread operator, you were forced to use the Array’s concat() method.

const fruits = [“apples”, “bananas”, “pears”];
const vegetables = [“corn”, “potatoes”, “carrots”];

const produce = […fruits, …vegetables];

console.log(produce);

Output :

[ ‘apples’, ‘bananas’, ‘pears’, ‘corn’, ‘potatoes’, ‘carrots’ ]

Tagged with: , , , , ,
Posted in ES6, JavaScript

ES6 Spread Operator


The spread operator, written with three consecutive dots ( … ), is new in ES6 and gives you the ability to expand, or spread, iterable objects into multiple elements.

Example 1: Array Elements Spread

const books = [“Mallik”, “Talks”, “Java”, “.com”];
console.log(…books);

output:

Mallik Talks Java .com

Example 2: Set Elements Spread

const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
console.log(…primes);

Output:

2 3 5 7 11 13 17 19 23 29

If you look at the output from the examples, notice that both the array and set have been expanded into their individual elements. Sets are a new built-in object in javascript in ES6.

Tagged with: , , , , ,
Posted in ES6, JavaScript

ES6 for…of Example Program – Replace first letter of String with Uppercase


Below example iterates days array using for…of operation in ES6 and replaces the first character of the day with upper case.

/*
* Programming Quiz: Writing a For…of Loop (1-4)
*/

const days = [‘sunday’, ‘monday’, ‘tuesday’, ‘wednesday’, ‘thursday’, ‘friday’, ‘saturday’];

for (const day of days ){
console.log(day.charAt(0).toUpperCase() + day.slice(1));
}

Below is the Output of the Program:

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Tagged with: , , , , ,
Posted in ES6, JavaScript

NgModule Properties in Angular 2


NgModule is a decorator function that takes a single metadata object whose properties describe the module. The most important properties are:

declarations – the view classes that belong to this module. Angular has three kinds of view classes: components, directives, and pipes.
exports – the subset of declarations that should be visible and usable in the component templates of other modules.
imports – other modules whose exported classes are needed by component templates declared in this module.
providers – creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app.
bootstrap – the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property.

Source: https://angular.io/

Tagged with: , , , , ,
Posted in Angular

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 674 other followers

Calendar
February 2019
M T W T F S S
« Jan    
 123
45678910
11121314151617
18192021222324
25262728  
Mallikarjun Gunda

This is Mallikarjun Gunda, I am working as a software professional. Blogging is my Passion. This blog contains the posts on Java related technologies and programming languages. I am happy to share my knowledge through the blogs.

Blog Stats
  • 296,368 hits
IndiBlogger
malliktalksjava.wordpress.c...
70/100