Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What do you mean by Control Flow Functions and how does Control Flow control the functions?

Answer»

A set of code which always operates in between multiple asynchronous function call is called Control Flow. You may describe it as a function because it takes some input and provides you or its next functions an output. Control Flow usually controls the function by using the following steps:- 

  • Control the order of execution 
  • Collect data 
  • Limit concurrency 
  • Call the next step in program 

We have three different patterns which can explain more about control functions :- 

  1. Control flow pattern #1: Series - an asynchronous for loop:- Consider a case when you have multiple programs and the first program provides a feed to the second program, and third to fourth in a sequential manner. So in this case we just need to trigger one async () operation and pass CALLBACK to it. This will trigger all remaining programs and provide you the expected results. 
  2. Control flow pattern #2: Full parallel - an asynchronous, parallel for loop :- Consider a case when our application requires feed from different other systems which may or may not require to run in a sequence. Whenever all PREREQUISITE programs are finished and provide a feed to our application then only our PROCESS will trigger. So this scenario we just have to worry about the available resources so that prerequisite applications should not consume all resources and later applications will always be on HOLD stage.  
  3. Control flow pattern #3: Limited parallel - an asynchronous, parallel, concurrency limited for loop:- In this flow a fresh async () function will call till the time application CONSUMES all the available resources and every operation will store the results of its operation. After successful completion of first async operation launcher() will call it again unless there is no application PENDING to run. Once our application achieves this stage then we will call final() for processing the final information and share the output/result with the user. 
2.

Can you describe a few commands of working in the file system  from your local machine or database?

Answer»

Node.js file SYSTEM module is capable to work on file either on your local system or database but working on file system we have to call require() method for calling a file server. This can be understood by the following example:- 

Var fs = require(‘fs’); 

Basic activities or operations which are required for working on file are as mentioned below:- 

  • Read a file :- We have to call/use fs.readFile() method for reading any file on our local system or any HTTP file. For example:- 
var http = require('http');  var fs = require('fs');  http.createServer(function (REQ, res) {    fs.readFile('demofile1.html', function(err, data) {      res.writeHead(200, {'Content-Type': 'text/html'});  res.write(data);      res.end();    });  }).listen(8080);  
  • Create a file:- For creating any new file we have three different METHODS which are as follows:-  fs.appendFile(); 
    fs.open();      fs.writeFile();
  • UPDATE a file:- For creating any new file we have two different methods which are as follows:- fs.appendFile(); 
   fs.writeFile(); 
  • Delete a file:- For deleting any file with file system module we have to use the following method:- fs.unlink() 
  • Rename a file:- For renaming any file with file system module we have to use the following method:- fs.rename() 
3.

Explain the difference between readFile and createReadStream in Node.js?

Answer»

Node.js is a runtime framework that has turned out to be FAMOUS with most coders and is utilized generally for creating server-side applications. Node.js is best known for making CONSTANT APIs and building another network of interoperability over the web. There are two manners by which a record can be perused and sent for execution in Node.js; readFile and CreateStream. Please see a few major differences in readfile and createStream as below:- 

  1. readFile load the entire record which you had set APART to peruse though createReadStream peruses all records in the parts of the size you have proclaimed.  
  2. The customer will get the information quicker on account of createReadStream interestingly with readFile.  
  3. In readFile, a record will first totally peruse by memory and after that moves to a customer yet in later CHOICE, a document will be perused by memory in a SECTION which is sent to customers and the procedure proceeds until every one of the parts is wrapped up. 
4.

What are Streams? Please explain a few streams type of Node.js?

Answer»

Streams are accumulations of information — simply like clusters or strings. What matters is that streams PROBABLY won't be accessible at the same time, and they don't need to fit in memory. This makes streams extremely amazing when working with a lot of information, or information that is originating from an outer source one piece at once.  

Notwithstanding, streams are not just about working with enormous information. They additionally give US the intensity of composability in our code. MUCH the same as we can create ground-breaking linux directions by funneling other littler Linux directions, we can do precisely the equivalent in Node with streams. 

Streams are extraordinary kinds of objects in Node that enable us to peruse data from a source or compose data to a goal consistently. There are 4 kinds of streams accessible in Node Js, they are  

  • Comprehensible − For perusing task.  
  • Writable − For COMPOSING task.  
  • Duplex − Used for both read and compose task.  
  • Change − A kind of duplex stream where the yield is figured DEPENDENT on the information. 
5.

Explain the mechanism of reading the content of a file in Node.js?

Answer»

Node.js file system module is capable of working on files either on your local system or database, but working on file system we have to call require() method for calling a file server. Through Node.js we can even open any http file and perform read content operation. 

NodeJs peruses the content of a document in a non-blocking, nonconcurrent way. Node JS utilizes its fs center API to manage DOCUMENTS. The simplest method to peruse the WHOLE SUBSTANCE of a document in nodeJs is with fs.readFile strategy. The following is a test code to peruse a record in NodeJs asynchronously and synchronously. 

Reading a file in node asynchronous/ 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 asynchronous/blocking  var fs = require('fs');   var contents = fs.readFileSync('DATA', 'utf8');  console.log(contents);
6.

Why Zlib is used in Node.js?

Answer»

The Zlib module provides a way to zip and unzip files. Zlib is a Cross-stage data compression library. It was composed by Jean-loupGailly and Mark Adler. In Node js, you can Zlib for Threadpool, HTTP solicitations, and reactions pressure and Memory Usage Tuning. So as to utilize zlib in node js, you have to introduce HUB zlib bundle. After ESTABLISHMENT, below is the test code to utilize Zlib. 

var Buffer = require('buffer').Buffer;  var zlib = require('zlib');  var input = NEW Buffer('lorem ipsum dolor sit amet');  var compressed = zlib.DEFLATE(input);  var output = zlib.inflate(compressed);

Following are a few important Zlib properties and Methods:- 

MethodDescription 

  • constantsReturns an object containing Zlib constants 
  • createDeflate()Creates a Deflate object 
  • createDeflateRaw()Creates a DeflateRaw object 
  • createGunzip()Creates a Gunzip object 
  • createGzip()Creates a Gzip object 
  • unzip()Decompress a string or buffer, using Unzip 
  • unzipSync()Decompress a string or buffer, synchronously, using Unzip 
  • deflate()Compress a string or buffer, using Deflate 
  • gzip()Compress a string or buffer, using Gzip 
  • gzipSync()Compress a string or buffer, synchronously, using Gzip 
  • inflate()Decompress a string or buffer, using Inflate 
  • inflateSync()Decompress a string or buffer, synchronously, using Inflate 
7.

What do you mean by libuv in Node.js?

Answer»

libuv is a fabulous asynchronous IO library. It has a high productive event loop, and additionally has a separate answer for io blocking activity. It has an interior laborer thread pool for io blocking operation(E.g. submit io blocking work through uv_queue_work). So it accomplishes incredible execution by consolidating both asynchronous event loops and thread pools for non-io blocking and io blocking activity. It is a decent DECISION for superior server.   

If the synchronous thread pool model is what you are used to on an everyday basis, you may find the asynchronous model somewhat hard, particularly when you have to decide when is the best time to discharge the "HANDLES". If you do not get that RIGHT, libuv will crash and make your troubleshooting difficult. 

libuv is a Cross-platform I/O abstraction library that supports asynchronous I/O based on event loops.It is written in C and released under the MIT Licence. 

libuv support Windows IOCP, epoll(4), kqueue(2), and Solaris event ports. Initially, it was DESIGNED for Node.js but later it is also used by other software projects. 

Reference : https://en.wikipedia.org/wiki/Libuv 

8.

What do you understand by Module in Node.js?

Answer»

A reusable block of code which may not impact the other codes through its presence is called a Module. Modules are presented in ES6. Modules are significant for MAINTAINABILITY, Reusability, and Namespacing of Code. 

Module in Node.js is a basic or complex functionality organized  in single or VARIOUS JavaScript documents which can be reused all through the Node.js applications.  

Every module in Node.js has its own unique circumstances, so it can't meddle with different modules or contaminate global modules. Additionally, every module can be put in a different .js record under a different envelope.  

Node.js actualizes CommonJS modules standard. CommonJS is a gathering of volunteers who characterize JavaScript guidelines for WEB server, work area, and REASSURE application. 

Node.js includes three types of modules: 

  1. Core Modules:- Node.js is a lightweight framework and core modules carry the minimal functionality of Node.js. 
  2. Local Modules:- Any Module which is locally created for one application and doesn’t have any scope outside the parent application is known as a Local Module.  
  3. Third Party Modules:- All external functionality which is available through export module can be imported and used in the application is called a Third Party Module. 
9.

How will you differentiate between Asynchronous and Non-blocking ?

Answer»

Asynchronous truly implies not synchronous. If we are making HTTP REQUESTS which are asynchronous, it implies we are not waiting for the server reaction. 

The term Non-Blocking is broadly utilized with IO. For instance non-blocking read/compose calls come back with whatever they can do and anticipate that the user should execute the call once more. Peruse will hold up until it has some information, and put calling thread to rest. 

An asynchronous consider demands an exchange that will be performed in its whole(entirety) yet will finish at some FUTURE time. Non-blocking: This capacity won't pause while on the stack. Synchronous is characterized as occurring simultaneously. Asynchronous is characterized as not occurring simultaneously. 

PLEASE REVIEW the below example to understand BETTER:- 

Synchronous & blocking 

  1. phone.waitForCall(); // Current thread is blocked 
  2. phone.getCall().answer(); 
  3. book.read(); 

Synchronous & non-blocking 

  1. while (!phone.hasCall()) { 
  2. book.readWithTimeout(someTime); 
  3. phone.getCall().answer();   // PhoneCall::answer is called here 
  4. book.read(); 

Asynchronous 

  1. // We can't tell the context where the callback is called. 
  2. // But it is definitely not the current context. 
  3. phone.onRing(PhoneCall::answer); 
  4. book.read(); 
10.

What is the significance of module.exports in Node.js?

Answer»

The module.exports or exports is an uncommon article which is incorporated into each JS record in the Node.js application as a matter of course. The module is a VARIABLE that speaks to current module and exports is an ITEM that will be uncovered as a module. Thus, whatever you allocate to module.exports or send out, will be uncovered as a module. Each Module in Node.js has its own functionality and that cannot interfere with the other modules.   

A module encapsulates related code into a solitary unit of code. This can be translated as MOVING every single related function into a document. Envision that we made a document called greetings.js and it contains the following two functions: 

module.exports = { printAdditionInMaths: functions()  { return "+"; },  printSubtractionInMaths: functions()  { return "-";} };

In the above example, module.export has exposed 2 functions which can be called out in any other PROGRAM as shown below:- 

Var mathematics = require(“./mathematics.js) mathematics.printAdditionInMaths(); mathematics.printSubtractionInMaths();
11.

What do you mean by Event Loop and how does it work in Node.js?

Answer»

A mechanism which is designed to handle async callbacks is known as Event loop. Node.js is a single threaded and event driven programming language. We can attach any listener on the request node and whenever it is triggered with a known request then listener will accept and process it based on the PREDEFINED callback functions which we have setup in our APPLICATION.    

At whatever point we are callingsetTimeout, http.get and fs.readFile, Node.js runs these tasks and further keeps on running other PROGRAMS without waiting for the output. At the point when the activity is done, it gets the output and runs our callback function.  

So all the callback functions are LINED in a circle, and will RUN individually whenever we receive the response. 

12.

Can we load a HTML code  into Node.Js?

Answer»

We can easily load HTML code into Node.Jsby making a change in the content TYPE.  In HTML Code content type is defined as “TEXT/plain” and for LOADING this into Node.Js we have to change it to “text/html”. PLEASE see below example for more detail:-  

fs.readFile(FILENAME, "binary", function(err, file) {  if(err) {   response.writeHead(500, {"Content-Type": "text/plain"});  response.write(err + "\n");  response.end();  return;  }  response.writeHead(200);  response.write(file, "binary");  response.end();  });

Now we have to modify the above code to load an HTML page instead of plain text like as below:- 

fs.readFile(filename, "binary", function(err, file) {  if(err) {   response.writeHead(500, {"Content-Type": "text/html"});  response.write(err + "\n");  response.end();  return;  }  response.writeHead(200, {"Content-Type": "text/html"});  response.write(file);  response.end();  });
13.

How can you resolve callback hells issue?

Answer»

Callback Hell no more with Promises and its nearby partner, GENERATORS. ... It comprises of numerous settled callbacks which makes code hard to pursue and investigate. One may unconsciously get captured in Callback Hell while MANAGING asynchronous logic. Callback hell is a marvel that torments a JavaScript designer when he attempts to execute different nonconcurrent tasks in a STEADY progression. You may use any of the below options for resolving the issue of callback hells: 

  1. Use async/await :- This option is very famous among DEVELOPERS because it will help you to write down your code in a synchronous manner although it is still asynchronous  
  2. Use a control flow library 
  3. Modularization: break callbacks into INDEPENDENT functions 
  4. Use generators with Promises :- This will make application code shorter and easier to understand. This will also help another programmer to enhance the old codebase as per new requirements.  
14.

What do you mean by Error-First Callback?

Answer»

The “error-first” callback  is also known as an “errorback”, “errback”, or “node-style callback”. Error-first callbacks are utilized to pass ERRORS and data too. You need to pass the error as the main parameter, and you MUST verify whether something went wrong. Additional arguments are utilized to pass data.  There are two rules for defining an error-first callback: 

  1. The first argument of the callback is reserved for an error object.If an error occurred, it will be returned by the first err argument. 
  2. The second argument of the callback is reserved for any SUCCESSFUL response data. If no error occurred, err will be set to null and any successful data will be returned in the second argument. 

Code example is as below:- 

fs.readFile(filePath, FUNCTION(err, data) {      if (err) {      // handle the error, the return is IMPORTANT here      // so execution stops here      return console.log(err)    }    // use the data object    console.log(data)  })
15.

What are the steps for deleting a file?

Answer»
  1. IMPORT fs module
  2. delete the file USING fs.unlink METHOD and name of file to be deleted as parameter.

Create a text file “demo_file_del.txt” file to be deleted.

var fs = require("fs");  //import fs module console.log("going to delete demo_file_del.txt file") fs.unlink('demo_file_del.txt', function(ERR) { // call unlink method) if (err) { return console.err(err); } console.log("File deleted SUCCESSFULLY") });

Result: 

  • going to delete demo_file_del.txt file
  • File deleted successfully
  • demo_file_del.txt was deleted.
16.

what are the steps for truncating a file?

Answer»

import fs module and declare buffer class

  1. Open the file using fs.open method
  2. Execute the method ftruncate to truncate the opened file. PROVIDE the name of the opened file , length of file after which the file will be TRUNCATED.
  3. Read the truncated file after successful truncation using fs.read method and buffer
  4. iclose the file using fs.close method

Example: Create a TEXT file named trnk.txt with Knowledgehut tutorials as text in it

Create a javascript code as follows. Save it as trnkexmpl.js

VAR fs = require("fs"); //import module var buf = new Buffer(1024); //define buffer   fs.open('trnk.txt', 'r+', function (err,fd) { if (err) { return console.error(err); } console.log("File opened"); //Truncate the open file) fs.ftruncate(fd, 12, function(err) { if (err) { return console.log(err); } console.log("File Truncated") console.log("Going to read same file")  fs.read(fd, buf, 0, buf.length, 0 ,function(err, bytes) { if(err) { return console.log(err);  } //PRINT only read bytes if(bytes > 0) { console.log(buf.slice(0, bytes).toString()); }   //Close the opened file fs.close(fd, function(err){ if (err) { console.log(err); } console.log("File closed successfully"); }); }); });   });  

Execute the code . You get the following result

  • File opened
  • File Truncated
  • Going to read same file
  • Knowledgehut
  • File closed successfully
17.

Does fs module methods support both synchronous and asynchronous forms and which method forms are preferred and why?

Answer»

Yes.Every method of fs module SUPPORTS both synchronous and asynchronous forms.

Asynchronous methods TAKE the first parameter of CALLBACK function as error and last parameter as completion function.

It is better to use an asynchronous method as it NEVER blocks as program during execution WHEREAS synchronous methods does block the program during execution.

18.

Explain chaining the streams?

Answer»

Chaining is

  • a mechanism to connect output of one stream to ANOTHER stream and create a chain of MULTIPLE stream operations.
  • normally used with piping operations.

Example: Create a text file dataSinput.txt with the following content.

  • Monday is first day of week
  • Tuesday is second day of week
  • Wednesday is third day of week

After executing following code.

var fs = require("fs"); //import fs module var zlib = require("zlib"); //import zlib module //creating a readstream to read our inputdatafile dataSinput.txt var readStream = fs.createReadStream("F://dataSinput.txt"); //create a COMPRESSED folder zlib var czlib = zlib.createGzip(); //creating a writestream(initially empty) which is destination for transferred data  var writeStream = fs.createWriteStream("F://dataSoutput.txt.gz"); //Use Pipe command to transfer from readstream to gzip.  //Pipe commands takes all data from readstream and pushes it to compressed writestream file   readStream.pipe(czlib).pipe(writeStream); console.log("File Compressed");

You get result as “File Compressed”. And compressed file dataSoutput.txt.gz as output Which CONSISTS of text file dataSoutput.txt.

19.

Explain piping the streams?

Answer»

Piping is 

  • a mechanism where output of one stream is provided as INPUT to ANOTHER stream 
  • normally used to get data from one stream and pass the data to another stream

No limit on piping operations.

Example: Create a text file dataSinput.txt with the following content.

  • Monday is first day of WEEK
  • Tuesday is second day of week
  • Wednesday is third day of week

After executing the following code you can view the contents in the outputfile.

var fs = require("fs"); //import fs module //creating a readstream to READ our inputdatafile dataSinput.txt var readStream = fs.createReadStream("F://dataSinput.txt"); //creating a writestream(initially empty) which is destination for transferred data  var writeStream = fs.createWriteStream("F://dataSoutput.txt"); //Use Pipe command to transfer from readstream to writestream.  //Pipe command takes all data from readstream and PUSHES it to writestream  readStream.pipe(writeStream);

Output in dataSoutput.txt can be seen as

  • Monday is first day of week
  • Tuesday is second day of week
  • Wednesday is third day of week
20.

Explain Duplex and Transform streams?

Answer»

DUPLEX: Duplex streams are streams that implement both readable and WRITABLE interfaces

Examples:

  1. TCP sockets
  2. zlib streams ( Compression LIBRARY functionality streams)
  3. cypto streams ( Cryptography functionality streams)

Transform: A type of duplex streams where output is in someway related to the input. LIKE duplex streams, Transform streams also implement both Readable and Writable interfaces.

Examples: 

  1. zlib streams ( Compression library functionality streams)
  2. cypto streams ( Cryptography functionality streams)
21.

Mention some of the interactions you can make with buffer data?

Answer»
  • Convert Buffer to JSON
  • Reading from Buffers
  • Concatenating Buffers
  • Compare Buffers
  • Copy Buffer

Example:

How to convert BINARY EQUIVALENT of STREAM xyz to JSON format:

create a javascript file with following code.

var BUF = Buffer.from('xyz'); console.log(buf.toJSON());

in the first LINE buf is the variable and Buffer is the Buffer class. Using toJSON method we can convert code as shown in the result below.

Execute the code : Following is the result

{ type: 'Buffer', data: [ 120, 121, 122 ] }

22.

Explain buffer concept in Node.js. Do we need to define any module to use buffer class?

Answer»

The buffers module provides a way of handling streams of binary data.

Nodejs implements Buffer using Buffer class. 

Typically, the movement of data is done with the purpose of processing it, or read it, and make decisions based on it. But there is a minimum and a maximum amount of data a process could take over time. So if the rate at which the data arrives is faster than the rate at which the process consumes the data, the excess data need to wait somewhere for its turn to be processed.

On the other hand, if the process is consuming the data faster than it arrives, the few data that arrive earlier need to wait for a certain amount of data to arrive before being SENT out for processing.

That “waiting area” is the buffer! It is a small physical location in your computer, usually in the RAM, where data are temporally GATHERED, wait, and are eventually sent out for processing during streaming.

Example: An example where you can see buffering in action is when you are trying to read an e-book( of size 500 pages with graphics) in google books. If internet is FAST enough, the speed of stream is fast enough to fill up the buffer and SEND out for further processing, then fill another one and send out for processing, till stream is finished.

If your internet connection is slow, Google books display a loading icon, which means gathering more data or expecting more data to arrive. When the buffer is filled up and processed, google books show the page. While displaying the page, more data continues to arrive and wait in the buffer.

No. Buffer class is part of Global Modules.

23.

How to fire an event and bind the event to an event handler?

Answer»
  1. import events module
  2. create an eventEmitter OBJECT
  3. create an eventHandler  

To fire an event use eventEmitter.EMIT(‘evenName’)

To BIND an event handler with an event eventEmitter.on(‘eventName’, event handler)

Example: Refer the following example.

// Import Events module var events = require('events'); // Create an eventemitter object var eventEmitter = new events.EventEmitter();//Create an event handler var myEventHandler = function () { console.log('I have completed'); } // Assign evenhandler to an event eventEmitter.on('complete', myEventHandler);  // Fire the complete event eventEmitter.emit('complete')

Following is the result after EXECUTING the code.

Result: I have completed

  • For firing an event , use  emit METHOD
  • For assigning an event, use on method.
24.

Explain Event driven applications , how is it different from callback function, module used and classes used with examples?

Answer»
  1. Node.js uses Events heavily. Most of Node.js API’s are BUILT on Event driven architecture.

Every action on a computer is an event.

Example: File OPENING is an event.

Objects in Node.js can fire events like createReadStream object FIRES when opening or closing a file.

Example: to read a stream of characters in existing file trnk.txt

var fs = require("fs"); var rdstream = fs.createReadStream('trnk.txt'); rdstream.on('open', function(){ console.log("File OPENED"); });  

Executing above code you will get result as 

File Opened

You can create, fire and listen to your events using Events module, eventEmitter class.

Events module and eventEmitter class is used to bind events and event-listener.

25.

Explain difference between blocking and non blocking program?

Answer»

Blocking program 

  1. executes very much in sequence
  2. Easier to implement the logic

 Example: Let us create text file named blk.txt

blk.txt

 A technology that has emerged as the frontrunner for handling Big Data processing is Hadoop.

Create a javascript code as follows and save as blk.js

VAR fs = require("fs"); var data = fs.readFileSync('blk.txt'); console.log(data.toString()); console.log('Program Ended');

Execute the code. The result is 

A technology that has emerged as the frontrunner for handling Big Data processing is Hadoop.

Program Ended

In this example, program BLOCKS until it reads the file and then only it proceeds to next statement or end the program.

Non Blocking program

  1. Do not execute in sequence
  2. In CASE a program needs to use any data to be processed, it should be kept within the same block to MAKE it sequential execution.

Example: Use the same input file defined for blocking code example.

Create a javascript code as follows and save as nblk.js

var fs = require("fs"); fs.readFile('blk.txt', function (err,data) { if (err) return console.error(err); console.log(data.toString()); }); console.log("Program Ended"); 

Execute the code. The result is

Program Ended

A technology that has emerged as the frontrunner for handling Big Data processing is Hadoop.

This example shows that program doesn’t WAIT for file reading and prints “Program Ended” first. At the same time, the program without blocking continues to read the file.

26.

What is npm and mention its components?

Answer»

npm is WORLD’s largest software repository. Globally, open source developers use npm to SHARE and borrow packages. Example, you NEED to install node and npm before getting necessary packages for ANGULAR development.Packages are needed to bring modularity to code development.   

npm consists of three distinct components:

  1. website – to discover packages and their dependencies (by searching), setup profiles for authentication, version control management 
  2. CLI (Command line interface) -  runs on a terminal which is the way developers interact with npm.
  3. registry – large public database of JAVASCRIPT software and meta-information surrounding it

Some of the uses of npm are:

  1. manage multiple versions of code and code dependencies
  2. update applications easily when underlying code is updated
  3. Adapt packages of code for your apps, or incorporate packages as they are.
27.

What do you mean by Event Driven Programming?

Answer»

In general programming terms, event-driven programming is a programming technique in which the flow of the program is determined by EVENTS such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs or THREADS.  

As we know, Node.js is a single threaded application but it can support multithreading through Event and callback function. Event Driven programming is running on Request and response technique. We have to define a target which may be any button or click event so whenever our application is going to receive a request on the target our application will ACCEPT and process that request, and provide a response BACK to the user. This is usually achieved through Callback function. You can review the below example for more reference:-

function addtoStudent(STUDENTID)  {  event.send("student.add" , {id: studentId})  }  event.on("student.add", function(event)  {   show("Adding New Student" +event.id);  });
28.

How will you uninstall or update any dependencies through NPM?

Answer»

Node Package Manager (NPM) provides two primary functionalities − 

  • Online vaults for node.js bundles/modules which are accessible on search.nodejs.org. 
  • COMMAND line utility for interacting with the requested/required repository which is included in the package installation, and to do version management and dependency management of Node.js bundles. 

www.npmjs.com hosts thousands of free packages to download and use. The NPM program is installed on your computer when you INSTALL Node.js. There might be a scenario when we are required to either uninstall a dependency or have to update an existing dependency, so please use the FOLLOWING command for uninstalling any dependencies through NPM: 

C:Nodejs_WorkSpace>npm uninstall <Name of dependency here> 

Please use the following command for updating any dependencies through NPM 

C:Nodejs_WorkSpace>npm update <Name of dependency here> 

To get the old behavior, use npm --depth 9999 update . As of npm@5.0.0 , the npm update will change package.json to SAVE the NEW version as the minimum required dependency. To get the old behavior, use npm update --no-save 

29.

What do you mean by Package Jason? Can you name some of its attributes?

Answer»

The PACKAGE.json file is the core of Node.js system. It is the main file of any Node.js project and contains the complete information about the project. Developers have to have a deep understanding of package.json file to work with Node.js. It is the first step to learn about development in Node.js. Package.jason is mostly used for DEFINING the PROPERTIES of a package and it is always present in the root directory folder of any Node js application. The most common attributes of Package.Jason are as following:- 

  • name - Name of the package 
  • version - Version of the package 
  • DESCRIPTION - Brief description of the package 
  • homepage - Homepage of the package 
  • AUTHOR - Author of the package 
  • contributors - Name of the contributors to the package 
  • dependencies - List out all dependencies and npm will automatically install all the dependencies described here.  
  • repository - Repository type and url of the package 
  • main - Starting point of the package 
  • keywords - Important keywords 
30.

Define some basic criteria for using node js in any project?

Answer»

Applications MADE using Node.js CREATE a single thread, which means it receives a request and processes it first before moving to another request. So if you are developing any streaming application or event based application, then Node.js is best suited for it. Some examples of such applications are as FOLLOWS:- 

  • Chat Applications:- In chat applications,where there are multiple users logged in and chatting with multiple agents, a fast and high performance server is needed to handle such multiple requests simultaneously. 
  • Gaming Applications:- Gaming applications are the best example of collaboration work where multiple teams are working on different modules and at the same time. To support such applications it is very necessary to keep a good control on VERSION management system. Node.js has a very powerful Event Loop feature which SUPPORTS the above scenario. It can handle multiple events at the same time, without blocking other components of the application.  
  • Advertisement Applications/Servers:-  Node.js is the best solution for accepting multiple requests for downloading the ads from the server, and its response time is very less.   
  • Streaming Applications:- In any applications which interact with online streaming server, users send multiple requests to servers for different queries. In this case we have to use Node.js because of its high accuracy and less CPU usage. 
31.

What are the GLOBAL &amp; LOCAL Installation of Dependencies? What command you should use to check already Installed Dependencies Which Are Globally Installed Using Npm?

Answer»
  • GLOBAL Dependencies:- We have to keep all global packages or dependencies into <user-directory>/npm directory. All global dependencies can only be used in the Command Line Interface function into any node.js but it cannot be directly imported using require () into any application. For INSTALLING any global package into Node project globally use -G flag. PLEASE use the following command for installing any Global dependency. 
  • Command :- C:Nodejs_WorkSpace>npm install express -g 
  • LOCAL Dependencies:- Any local package gets installed in the local mode only,ie into Local_modules directory PRESENT in the folder where the node js application is installed or kept. Local dependencies can only be accessed by require() function. For installing the node project into local directory, or installing any local dependency, we have to use the following command:- 
  • Command:- C:Nodejs_WorkSpace>npm install express 
  • We can use following command for fulfilling the above purpose:- C:Nodejs_WorkSpace>npm ls -g 
32.

What is the use of underscore variable in REPL?

Answer»

Underscore variable is a special kind of variable which USUALLY stores the value of its last execution result. Whenever you need to use the OUTPUT of one MODULE to the input of next module you may use this variable. It serves asimilar purpose as $? in bash. Please find below an example for a more detailed explanation:-  

Use _ to get the last result. 

C:Nodejs_WorkSpace>node 

> var x = 10  undefined  > var y = 20  undefined  > x + y  30  > var sum = _  undefined  > console.log(sum)  30  undefined  >

In Version 6.x or higher Underscore variable gives you the following result:- 

> [ 'a', 'b', 'c' ]   [ 'a', 'b', 'c' ]   > _.LENGTH 3   > _ += 1  

EXPRESSION assignment to _ now disabled.  

4   > 1 + 1   2   > _   4

In older version you will get a different result:- 

> [ 'a', 'b', 'c' ]  [ 'a', 'b', 'c' ]  > _.length  3  > _ += 1  4  > 1 + 1  2  > _  2
33.

What is REPL in Context of Node?

Answer»

Node.js is an open source server-side JavaScript run-time condition based on Chrome's JavaScript Engine(V8). Node.js is utilized to structure quick and adaptable applications and is an occasion driven, non-blocking I/O model.  

REPL (READ, EVAL, PRINT, LOOP) is a PC situation like Shell (Unix/Linux) and direction brief. A command is entered and the system responds with an output. The hub accompanies the REPL condition when it is INTRODUCED, and the Framework ASSOCIATES with the client through yields of directions/articulations utilized. 

Node.js or Node comes bundled with a REPL environment that performs the following desired tasks. 

  • Read : It peruses the contributions from clients and parses it into JavaScript information structure. It is then put away to memory.  
  • Eval : The parsed JavaScript information structure is assessed for the outcomes.  
  • Print : The outcome is printed after the assessment.  
  • Loop : Loops the information order. To leave NODE REPL, press ctrl+c TWICE 

We have repl module which is available for standalone applicationsas well,  and can be called through below command:- 

const repl = require('repl'); 

34.

What tools can be used to assure consistent style?

Answer»

The following tools are very popular:- 

  1. ESLint:- This is ALSO an open source linting utility which helps DEVELOPER to overcome very common errors and also provides flexibility to developers for creating their own linting rules.   
  2. JSCS:- This is also a code style linter tool which was merged with ESLint in April 2016. 
  3. JSLint :- JSLint is a code quality tool that takes a JAVASCRIPT source and scans it. On the off chance that it finds an issue, it restores a message portraying the issue and a surmised area inside the source. The issue isn't always a syntax error, despite the FACT that it frequently is.JSLint sees some style conventions just as auxiliary issues. 
  4. JSHint:- this is a STATIC Code Analysis Tool for JavaScript. JSHint is a network driven instrument that identifies mistakes and potential issues in JavaScript code. Since JSHint is so adaptable, you can, without much of a stretch, alter it in the nature you anticipate that your code should execute. JSHint is open source and will consistently remain along these lines. 
35.

What are the disadvantages of Node.js?

Answer»

Disadvantages of Node.js are mentioned as below:- 

  1. Library SUPPORT System:- Node.js language does not have its own library support system so developers have to depend upon external sources. For example, if you want to process any image, in cases such as fetching data from database or data parsing,  developers have to take help from a common library.  
  2. Asynchronous Programming Model:- Node.js programming SUPPORTS asynchronous programming model which is advised if you want to make a scalable or flexible application. But the majority of developers observed that this model was more difficult as compared to linear programming. It is a very tedious task to FIND out an error or FAULT functions in this type of programming model.  
  3. Unstable Application Programming Interface:- It has been observed that API is not the same in the application developed in Node.js, so many developers face difficulties or are bound to make changes in their code to match with the LATEST available API of Node.js. 
36.

What are the advantages  of Node.js?

Answer»

Advantages of Node.js are mentioned as below:- 

  1. Easy Scalability:- Applications which are developed on Node.js are easy to scale in horizontal and VERTICAL directions. 
  2. Easy to Learn:- Node.js is very easy to learn and implement. It can be easily used in Frontend and backend. This is the only reason why this is so popular among developers. 
  3. Fullstack Language:- Node.js is a fullstack language which means it can be used at Server side and client side applications. A single developer can handle both frontend and backend application which results in saving time and money. 
  4. High Performance:- An application developed on Node.js performs very well in the runtime as it directly compiles the code into Machine code which helps in easy maintaining and  implementing of the code.  
  5. Open SOURCE Runtime Environment:- Node.js also provides a FUNCTIONALITY to caching data into a single module, which helps in STORING the data in application memory. So at runtime there should not be any buffering issue and it is much faster as compared to other languages.  
37.

What is Test Pyramid?

Answer»

Test Pyramid CONCEPT was given MIKE Cohn.  Its essential POINT is that you should have many more low-LEVEL unit tests than high level end-to-end tests running through a GUI. A test pyramid depicts the PROPORTION of what number of unit tests, reconciliation tests and E2E test you ought to compose.

38.

What do you mean by Stub?

Answer»

Stubs are utilized during Top-down combination testing, so as to reenact the CONDUCT of the lower-level modules that are not yet COORDINATED. Stubs are the modules that go about as impermanent substitution for a considered module and give a similar yield as that of the real item.  

Stubs are likewise utilized when the product needs to collaborate with an outside framework. 

Stubs are functions or programs that mimic the practices of component or modules. It gives predetermined responses to FUNCTION calls made during testing. 

Stub  Workflow 

In the above figure it is clearly STATED that Module 1, 2 and 3 are ready for testing whereas all remaining Modules are still in development. Order of Integration is as below:- 

  • 1,2 
  • 1,3 
  • 2,Stub 1 
  • 2,Stub 2 
  • 3,Stub 3 
  • 3,Stub 4
39.

What are the key benefits of using Node.js over other scripting languages?

Answer»
  1. No Buffering: Applications made on Node.js never support any information. These applications just yield the information in pieces. 
  2. Single-Threaded but highly Scalable: Node.js utilizes a solitary threaded model with event looping. Event mechanism helps server to REACT in a non-blocking WAYS and makes server highly scalable as opposed to conventional servers which create limited threads to handle requests. Node.js utilizes a single threaded program and the same program can service a larger number of requests than traditional servers like Apache HTTP Server. 
  3. Fast: Based on Google Chrome's V8 JAVASCRIPT Engine, Node.js library is extremely quick in CODE execution. 
  4. Asynchronous and Event Driven: All APIs of Node.js library are asynchronous that is non-blocking. It basically implies a Node.js based server never trusts that an API will return data. Server moves to next API after calling it and a warning component of the Events of Node.js causes server to get reaction from the past API call. 
40.

What do you understand by Asynchronous API?

Answer»

JavaScript is asynchronous in nature as is Node. Asynchronous computer programs have a structure design which guarantees the non-blocking code execution.  

Non-blocking code doesn't forestall the execution of bit of code. By and large in the event that we execute in a Synchronous way,i.e in a steady progression, we pointlessly STOP the execution of  code which does not upon the one you are executing.  

An asynchronous API makes a scheduled request for resources, services or data at a later time when they are available.  In other words, asynchronous code executes WITHOUT having any reliance or organization. This improves the framework effectiveness and throughput.) 

Asynchronous computer programs allow quicker execution of projects however it is at a higher cost. Truth is stranger than fiction, it's hard to program and more often than not we wind up having callback hellfire situations.  

This instructional exercise is tied in with clarifying every one of the Asynchronous situations which you may confront while coding. 

All APIs of Node.js LIBRARY are asynchronous that is non-blocking. It BASICALLY implies a Node.js based server never trusts that an API will return information. Server moves to next API SUBSEQUENT to calling it and a notice instrument of Events of Node.js causes the server to get a reaction from the past API call. 

41.

What do you mean by Node.js? What is the contrast between Node.js and Ajax?

Answer»

Node.js is a web application system based on Google Chrome's JavaScript Engine(V8 Engine).  

Node.js accompanies runtime condition on which a JavaScript based content can be deciphered and EXECUTED (It is analogous to JVM to JAVA bytecode). This runtime permits to execute a JavaScript code on any machine outside a program. As a RESULT of this runtime of Node.js, JavaScript presently can be executed on server too.  

Node.js likewise gives a RICH library of DIFFERENT JavaScript modules which facilitates the development of web application utilizing Node.js to incredible degrees.  

Node.js = Runtime Environment + JavaScript Library 

42.

Explain spawn() and fork() in  Node.js?

Answer»

Node.js follows a single-threaded EVENT loop model architecture. One process in one CPU is not enough to handle the application WORKLOAD so we create CHILD processes.“child_process” module supports child processes in Node.js. These child processes can communicate with each other using a built-in messaging system. Child processes could be created in four different ways Node: spawn(), fork(), exec(), and execFile().

spawn() method brings up the child processes asynchronously. It is a command designed to run system commands that will be run on its own process. In spawn() no new V8 instance is created and only one copy of your node module is active. When your child process returns a large amount of data to the Node spawn() method could be used.

Syntax:

child_process.spawn(command[, args][, options])

Spawn method returns streams (stdout & stderr) and it’s main ADVANTAGES are

  • Low memory footprint
  • Handle data in buffered chunks.
  • Evented and non-blocking

In fork() a fresh instance of the V8 engine is created. fork() method could be used as below:

Syntax:

child_process.fork(modulePath[, args][, options])

In fork()  a communication channel is ESTABLISHED between parent and child processes and returns an object. We use the EventEmitter module interface to exchange messages between them.

43.

Define libuv library?

Answer»

libuv is a multi-platform library of Node.js that SUPPORTS asynchronous I/O. It’s written in C.It was developed for Node.js, but it’s also used by Luvit, Julia, pyuv etc.libuv library handles file system, DNS, child processes, pipes, signal handling, POLLING and streaming.libuv provides the event loop to Node.js.The important features of libuv are:

  • Full-featured event loop
  • Asynchronous TCP & UDP sockets
  • Child processes
  • Thread pool or Worker Pool, that offloads work for some things that cannot be done ASYNCHRONOUSLY at the OS level.
  • Signal handling

In event-driven programming, an application follows certain EVENTS and respond to them when they occur. libuv gathers events from the operating system or other sources of events and then user registers callbacks to be called when an event occurs.

Some examples of events are:

  • The file is ready for writing
  • Time out of a timer

Libuv also provides two types of abstractions to users alongside  These are handles and requests. Handles represent long living objects like TCP server handle where its connection callback is called every time when there is a new connection. Requests are short-lived operations performed on the handle like write requests to write DATA on a handle.

44.

What are Promises?

Answer»

Promises in simple words could be explained as advanced call back functions. Whenever multiple callback functions needed to be nested TOGETHER Promises could be used. Promises avoid the callback hell PRODUCED by nesting together many callback functions. A promise could take up three states defined by the 'then clause'. Fulfilled state, rejected state, and pending state which is the initial state of promise.

Let’s take the example of reading a file and parsing it as JSON

1. Synchronous method of writing the code

function readJSONSync(filename) {   return JSON.parse(fs.readFileSync(filename, 'utf8')); }

2. Asynchronous method of writing the code using callback. Introducing callbacks make all I/O functions asynchronous.

function readJSON(filename, callback){   fs.readFile(filename, 'utf8', function (err, res){     if (err) return callback(err);     callback(null, JSON.parse(res));   }); }

Here a callback PARAMETER confuses a bit so we replace it with promise

3. IMPLEMENTATION Using Promise

function readFile(filename, enc){   return new Promise(function (fulfill, reject){     fs.readFile(filename, enc, function (err, res){       if (err) reject(err);       else fulfill(res);     });   }); }

Here we use “new Promise” to construct the promise and pass a function to the constructor with two arguments. The first one fulfills the promise and the second one rejects the promise.

To start working with promises we need to install the “promise” module first using the command

“npm install promise”  

45.

Define test pyramid with an example?

Answer»

Test pyramid is the pictorial representation of the RATIO of unit tests, integration tests and end-to-end tests required for developing a good quality node.js project.

  • Usually, a large number of low-level unit tests are written.
  • Comparatively less number of integration tests are written that tests how MODULES interact with each other.
  • Fewer end-to-end tests are written that tests the system as a whole.

Unit tests help to check the working of a single component or module. All dependencies are stubbed providing tests for exposed METHODS. Modules used for Node.js Unit Testing are:

  • Test runners like Mocha
  • Assertion library like Chai
  • Test spies, stubs and mocks like Sinon

Some of the above tools could also be used for integration tests for eg: SuperTest, Mocha and Chai that detects the defects in the early stage itself. Integration tests run FASTER than end-to-end tests.

Testing your application through its user interface is the most popular end-to-end way of testing for any application. End-to-end tests provide us with confidence that our system works all well together. The main disadvantage of end to end testing is that it requires a lot of MAINTENANCE and run pretty slowly.

46.

What is REPL in Node.js?

Answer»

REPL module in Node.js is Read-Eval-Print-Loop (REPL) implementation. It’s just like a SHELL and command prompt.REPL is available both as a standalone program or included in other applications. It can be accessed using the command:

“const repl = REQUIRE('repl');”

REPL accept individual lines of user input, evaluate them and then output the result. Input and output use stdin and stdout, respectively, or use any Node.js stream.REPL is mainly used for testing, debugging, or experimenting as it helps to execute ad-hoc javascript statements. The repl module exports the “repl.REPLServer” class which supports automatic completion of multi-line inputs, Emacs-style line editing,  ANSI-styled output, saving and RESTORING current REPL session state, error recovery, and customizable evaluation functions. REPL environment could be started by the opening terminal in case of Unix/Linux or command prompt in case of windows and typing “node”. Some of the commands supported by the REPL environment are below:

  • .break - In case of a multi-line expression, entering the .break command (or pressing the <ctrl>-C key combination) will ABORT further processing of the expression.
  • .clear - RESET  the REPL to an empty object
  • .exit - Causes the REPL to exit.
  • .help - Show the list of commands.
  • .save filename - Save the current REPL session to a file.
  • .load filename - Load a file into the current REPL session.
  • .editor - Enter REPL into editor mode (<Ctrl>-D to finish, <ctrl>-C to cancel).
47.

Explain types of streams in Node.js?

Answer»

Streams are abstract interface available with Node.js.The stream module HELPS in implementation of streaming data. There are four TYPES of streams.

  • <Readable> for the reading operation
  • <Writable> for the writing operation
  • <Duplex> for both reading and writing operations
  • <Transform> is a derived from Duplex stream that computes available input.

The important events on a readable stream are:

  • The data EVENT, where the stream passes a chunk of data to the consumer.
  • The end event, which happens when there is no more data to be used from the stream.

For eg:

Reading a file “input.txt”

var fs = require('fs'); var readableStream = fs.createReadStream('input.txt'); // creates readable stream                  var data = ''; readableStream.on('data', function(txt) {    // data event produces the flow of data     data+=txt; }); readableStream.on('end', function()  // end event is triggered when no data to read {     console.log(data); });

The important events on a writable stream are:

  • The write event, that signals that the writable stream can receive more data.
  • The finish event, that is produced when all data has been written to the underlying system.

For eg:

Write “Hello World “ to file.txt

var fs = require("fs"); var data = 'Hello world'; var writerStream = fs.createWriteStream('file.txt');  // Create a writable stream writerStream.write(data,'UTF8'); // Write the data to stream  // Mark the end of file writerStream.end(); writerStream.on('finish', function() {  // finish triggered when all data is written to     console.log("Write completed."); });

PIPING the streams is one of the most popular mechanisms in Node.js programs where output of one stream is provided as the input to another stream.For eg:

var fs = require("fs"); var readerStream = fs.createReadStream('example.txt'); // Readable stream var writerStream = fs.createWriteStream('exampleOutput.txt'); // Writable stream readerStream.pipe(writerStream);// Pipe the readable stream as input to writable stream console.log("Program Ended");
48.

What are the API functions available in Node.js?

Answer»

There are two types of API functions available in Node.js:

1.Synchronous or BLOCKING functions where all other code execution is blocked till an I/O event that is being waited on completes. These are executed synchronously one after the other.

For eg: 

Reading a file called ‘file.txt’

const fs = require('fs'); const data = fs.readFileSync('file.txt’); // blocks here until file is read

Here the execution of further lines in the program will be blocked. If any error is thrown it needs to be caught immediately to avoid the crashing of the program.readFileSync() completely reads the CONTENT to the memory and then prints the data in the console. The blocking function has an adverse effect on the APPLICATION’s performance.

2.Asynchronous or Non-blocking functions are another type of API functions where multiple I/O calls can be performed without the execution of the program being blocked.

For eg: 

Reading a file “file.txt”

const fs = require('fs'); fs.readFile('file.txt’, function(err, data) => {   if (err) throw err;  });

Here reading of the file (readFile()) doesn’t block further execution of the next instruction in the program. The above function takes the file name and passes the data of the file as a reference to the callback handler. Then the file system object remains ready to take up any other file system operation. Asynchronous API functions increase the throughput by INCREASING the number of instructions handled per cycle time.

49.

What is call back and call back hell in Node.js?

Answer»

A callback function is called at the end of a SPECIFIC task or simply when another function has finished executing. Callback functions are used exclusively to support the ASYNCHRONOUS feature or non-blocking feature of Node.js. In the asynchronous programming with Node.js, servers don’t wait for any action like API call to complete to start a new API call.

For eg

Let’s  read a FILE say “input.txt” and print its output in the console.The synchronous or blocking code for the above requirement is shown below:

var fs = require("fs"); var data = fs.readFileSync('input.txt');  // execution stops and waits for the read to finish console.log(data.toString()); console.log("Program Ended");  Let’s rephrase the code with the callback function. var fs = require("fs"); fs.readFile('input.txt', function (err, data) {    if (err) return console.error(err);    console.log(data.toString()); }); console.log("Program Ended");

Here program does not wait for reading the file to complete but proceeds to print "Program Ended".If an error occurs during the read function readFile(), err object will contain the corresponding error and if the read is successful data object will contain the contents of the file. readFile() passes err and data object to the callback function after the read operation is complete, which finally prints the content.

Pyramid of Doom or Callback HELL happens when the node.js programs are very complex in nature and having HEAVILY nested callback functions. The name is attained by the pattern caused by nested callbacks which are unreadable.

For eg

Let’s assume that we have 3 different asynchronous tasks and each one depends on the previous result causing a mess in our code.

asyncFuncA(function(x){            asyncFuncB(x, function(y){                  asyncFuncC(y, function(z){                      ...                 });             });       });

Callback hell could be avoided by the following methods :

  • Handling all errors immediately
  • Splitting the callbacks into smaller and independent functions
  • Declaring callback functions beforehand.
  • Libraries like Async.js adds a layer of functions on top of your code reducing the complexity of nested callbacks.
  • Usage of Promises where async code could be written that handles errors due by the usage of try/catch-style error handling.
50.

What is npm?

Answer»

Npm or Node Package Manager is the default package manager for Node.js.It works as:

  1. An online repository called as npm registry USED for the open-source Node.js projects.npm registry is a large DATABASE with around half a million packages. DEVELOPERS can download from and publish packages to the npm registry.
  2. Npm is also a  command-line utility for interacting with an online repository that helps in package installation, version management, and dependency management.

Few of the IMPORTANT  npm commands are:

  • Any package can be installed  by running a simple command

“ npm install <name of the package> “.

This will install the module under the path, “./node_modules/”. Once installed the module could be used just like they were built-ins. Dependency management could also be done with npm. Our node project will have a package.json which will have all the dependencies needed for our project. If we perform “npm install” from project root all the dependencies listed in the package.json file will be installed.

  • “npm init” Here package.json file is created that is where all dependencies are included.
  • “npm update <package_name>”  where the specific package is updated with new features
  • “npm uninstall <package_name>” where the specific package is uninstalled. It’s then removed from the “node_modules” folder.
  • “npm list” is used to list all the packages installed.
  • npm help” is the built-in help command.To get help for a particular command, use

“npm <command> -H