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 is Stub in Node JS?

Answer»

It is the PROCESS of creating fake endpoints in code so that we can delay writing complex code.

2.

What is Promises in Node JS?

Answer»

It is a RETURNED VALUE by an asynchronous FUNCTION to indicate the COMPLETION of the processing carried out by the function.

Example

var promise = doSomethingAync()

promise.then(onFulfilled, onRejected)

3.

What are the exit codes in Node.js? Can you list a few exit codes?

Answer»

Exit CODES are the specific codes that can be used to END a process. Some of the examples of exit codes are, Uncaught Fatal Exception, Fatal ERROR, Non-function Internal Exception Handler, Internal Exception handler Run-Time Failure, Internal JavaScript Evaluation Failure, etc.

4.

What do you mean by “streams”? What are the different types of streams in Node.js?

Answer»

Streams are the objects that allow and enable the CONTINUOUS process of reading the data from the source code and WRITING the data to the destination.

Streams are of four types:

  • FACILITATE reading operation (READABLE).
  • Facilitate writing operation (Writable).
  • Facilitate both reading and writing operations (Duplex).
  • Kind of duplex stream that performs the computations based on the available INPUTS (Transform).
5.

How to call multiple Promises?

Answer»

Promise.all([p1, P2]).then(VALUES => {
   console.log(values); // [7, "123"]
});

6.

What is the use of REPL in node JS?

Answer»

The Read EVAL Print LOOP (REPL) performs these four tasks - Read, Evaluate, Print and Loop. The REPL is used to execute ad-hoc Javascript functions. The REPL shell allows direct entry of javascript into a shell PROMPT and evaluates the results. REPL is very critical for testing, debugging, or experimenting.

7.

What is nodemon and how it can we used?

Answer»

Nodemon is that tool which helps to develop application based on node.js by automatically re-initiating the application of node WHENEVER the file changes inside the DIRECTORY get detected.

It does not need any further changes to the code or the development method. Nodemon is the REPLACEMENT wrapper of Node, to practice Nodemon replace the node WORD on the line of command at the time of executing the script

8.

How can we avoid callbacks?

Answer»

We can avoid callback hell by different AVAILABLE solutions, as mentioned below.

Promises: The promise is s result of an asynchronous operation. We can create a promise on these three STATES:

  • Pending: When the initial state is not fulfilled or rejected.
  • Fulfilled: When the operation gets completed successfully.
  • Rejected: When the operation gets failed.

Generators: These are functions that can be RESUMED and paused. It doesn’t get executed immediately when called. Instead, it returns a generator object or generator object with which we can control the execution of the function.

Note: After learning the basics of Node, if you are looking for what more to learn, you can start with meta-programming, protocols, and much more. We have created a list of node interview QUESTIONS to help them use this LANGUAGE to solve complex problems.

9.

How to send Email using Node.js?

Answer» RELATED ARTICLE: How to SEND EMAILS USING Node.js
10.

What is package.json?

Answer»

package.json is the most important FILE of any Node.js project and it CONTAINS the metadata of the project. It is USED to give information to NPM that allows it to IDENTIFY the project. It handles the project's all dependencies. It is placed on root of any project.

11.

What is callback function in NodeJS?

Answer»

A CALLBACK function is done at the completion of a task. This function allows other CODES to be run in the meanwhile and prevent blocking. Because Node.js is an asynchronous platform, it relies heavily on the callback function. In addition, the APIs also SUPPORT CALLBACKS.

12.

How to install Node JS?

Answer»
  • GO to the Nodejs.org SITE and download the binary files and Windows installer.
  • Run the Windows installer.
  • Follow the instructions on the screen for accepting the license agreement, clicking the NEXT button a few TIMES and allowing the default settings.
  • You will have to restart your COMPUTER. Remember that you may not be able to run Node.js until you restart your computer.
  • Make sure you have installed Node by running simple commands just to see what version GOT installed.
Related Article: How to install node js
13.

Why we used NPM in Node js?

Answer»

The NPM PROVIDES two main FUNCTIONALITIES:

  • It is the online repository for all of the Node.js packages.
  • It is the command LINE UTILITY for installing, version management and DEPENDENCY management of the Node.js packages.
14.

What are the advantages of Node JS?

Answer»
15.

What is Node.js and why it is used?

Answer»

Node.js, as open-source server environment, runs on various platforms such as Windows, UNIX, Linux, ETC. The anchor of the MEAN stack, Node.js is also one of the most popular server platforms in the world.

Why it is used?
  • It is asynchronously programming, runs single-threaded, non-blocking which is very memory efficient.
  • It can operate file various operations like create, open, write, READ, delete, and close files on the server and can collect FORM DATA.
16.

What are the pros and cons of using promises instead of callbacks?

Answer»

Here are the pros of using PROMISES over callbacks:

  • BETTER DEFINED and organized control flow of asynchronous logic.
  • Highly reduced coupling.
  • We have integrated error handling.
  • Enhanced readability.
Cons of using Promises over callbacks:
  • It kills the purpose of asynchronous non-blocking I/O.
  • Only one object can be returned.
  • We cannot RETURN MULTIPLE arguments.
17.

What is spawn in Node JS?

Answer»

The spawn is a method in NodeJS that spawns an external application through a new process and finally RETURNS a streaming interface for I/O. It is EXCELLENT for handling applications that produce a large amount of data or for working with streams of data as it reads in.

Example

Here’s an example how CHILD process have the ability to USE the spawn method:

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

18.

How do you write a callback function in node JS?

Answer»

A callback function is an asynchronous equivalent for a function. It's called at the completion of each and every TASK. In Node.js, callbacks are generally USED, and all the APIs of Node are written in a way to SUPPORT callback functions.

When a function starts reading a file, it returns the control to the execution ENVIRONMENT immediately so that the next request can be executed, and this is a perfect example of a callback function.

Example

Here’s how to write a callback function in Node.js:

VAR myCallback = function(data) {
  console.log('got data: '+data);
};

var usingItNow = function(callback) {
  callback('get it?');
};

19.

Which is more secure SOAP or REST?

Answer»

The point of differences mentioned below will help you to understand which ONE is more secure and when:

  • If standardization and security are the main goals, then SOAP should be considered as the stronger one to practice as the WEB Services. Also, SOAP offers WS-Security which is like an extra perk to the enterprise.
  • The REST API is compatible with a number of types of data outputs including JSON, XML, CSV while SOAP is able to handle XML only. With the help of REST using JSON helps to cut down a lot on the expenses.
  • REST is further advanced, therefore when the next endpoint requests one query completed beforehand, the development of API can make use of the data that too from the earlier request. Whereas, SOAP IMPLEMENTATIONS need to PROCESS all the queries each and every single time.

Although it sounds as if SOAP is more advantageous than REST, yet one good REST implementation can be really beneficial for an enterprise rather than using the poorly-designed SOAP API. And SOAP possesses in-built error handing to communicate ERRORS through the specification of WS-ReliableMessaging. Whereas, REST needs to send the transfer again every time it encounters one error.

20.

Why we use Bodyparser in node JS?

Answer»

It extracts the complete body PORTION owned by the stream of the incoming requests and exposes this extraction on the “req.body like something that is easier to interact with. This renders the user the middleware that uses the nodeJS or the zlib for unzipping the incoming DATA of request if it is zipped PLUS stream-utils or the raw-body in order to anticipate the full and raw CONTENTS belonging to the body of the request before "parsing it".

21.

How do you secure an API in Node.js?

Answer»

The paper “The Protection of INFORMATION in Computer Systems” by JEROME Saltzer and Michael Schroeder, cited some 8 PRINCIPLES with the help of which information WITHIN the computer systems can be stored efficiently. These are mentioned below :

  • Least Privilege
  • Fail-Safe Defaults
  • Mechanism Economy
  • Complete Meditation
  • Open Design
  • Privilege Separation
  • Least used Mechanism
  • Psychological Acceptability
22.

Are promises better than callbacks?

Answer»

With the help of Promises, Handling error across numerous asynchronous calls has BECOME more EFFORTLESS in comparison to what it was at the time of USING callbacks. Also, having the privilege to not provide any callbacks makes the CODING look even cleaner. On the contrary, callbacks present the mechanism of control flow. And they only inform the users about how the application flows, and not REALLY the information of what it does.

23.

What is REST API in node JS?

Answer»

Representational State Transfer or REST is a standard web-based architecture. REST makes use of the HTTP Protocol. It twirls around resources where each and every element is ONE resource and the resource is obtained by the common interface with the HELP of standard HTTP methods. This was first PROPOSED by a man named Roy Fielding in the year 2000. The REST Server solely renders entrance to resources as WELL as REST client accesses plus modifies these resources with the help of the HTTP protocol. And here each and every resource is RECOGNIZED by URIs or by global IDs. It uses numerous representations to present the resource such as text, or JSON, or XML, etc.

24.

Why we use express in node JS?

Answer»

ExpressJS is one prebuilt framework of NodeJS that can assist the users in building server-side web apps faster plus smarter. Simplicity, flexibility, minimalism, scalability are a few of its many CHARACTERISTICS and as it is BUILT inside NodeJS itself, Express inherited its execution as well.

ExpressJS streamlined coding in Node JS to a great extent and provided programmers some extra features to increase their coding of the server-side. There is no DOUBT in the FACT that it is the most famous frameworks of all in today’s TIME.

25.

Why node is faster than others?

Answer»

Multiple reasons are listed below:

  • In the comparison of HTTP servers, it provides the non-blocking of the input/output.
  • Node reduces the TOTAL number of servers that serve an equal amount of requests.
  • This uses the single process for managing the multiple requests.
  • By using the single-thread process, the COMPUTING speed will get increased and it ALSO saves a lot of space.
48. Why we used async & await?

Async and await are used to make the code easier to write and read. Also, the agenda behind rolling out this feature is to deal with the promises and functions chaining in the Node. Where the functions do not need to be chained just one after another, SIMPLY call the await function that returns the promise. On the other hand, the function async should be declared before returning a promise by awaiting a function.

26.

What is V8 Engine in Node JS?

Answer»

V8 Engine is Google's open-source javascript and written in C++. It is used INSIDE Google Chrome. It was first designed to increase the performance of JavaScript execution inside WEB BROWSERS.

27.

What is EventEmitter in Node.js?

Answer»

EventEmitter class lies in the events module and is accessibly through the following syntax:

//IMPORT events module
var events = require('events');
//create an eventEmitter object
var eventEmitter = new events.EventEmitter();

In CASE an EventEmitter INSTANCE is facing error, it emits 'error' EVENT. When a new LISTENER is added, the 'newListener' event gets fired and when a listener gets removed, 'removeListener' event gets fired.

28.

What are the local installations of dependencies?

Answer»

Local mode is the package installation in the node-modules directory in the same folder where Node APPLICATION is stored. By default, the Node Package MANAGER (NPM) installs dependencies in the local mode. Most locally deployed packages are also accessible via require(). In ORDER to install a Node PROJECT locally, you need to follow the SYNTAX.

29.

What are the global installations of dependencies?

Answer»

They have globally INSTALLED packages or dependencies that are stored in the /NPM directory. These dependencies can be used in Command Line Interface (CLI) of any NODE.js. However, they cannot be imported USING REQUIRE () command in Node application directly. In order to install a Node project globally, you need to use -g flag.

30.

Why is the importance of a consistent style? What tools can help you assure a consistent style?

Answer»

CONSISTENT style can help your team members modify projects EASILY WITHOUT the need to learn a new style for every PROJECT. Some of the useful tools are Standard and ESLint.

31.

What is the use of CORS in Node JS?

Answer»

CORS is a Node.js package USED for PROVIDING a Connect/Express middleware.

Example

app.use(function(REQ, RES, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

32.

What is Tracing in Node.js?

Answer»

Tracing is a MECHANISM in Node.js to provide a CENTRALIZED tracing information method, which is generated by V8, Node.js CORE, and the userspace CODE. It can be enabled with the --trace-event-categories command-line FLAG or by using the trace_events module.

33.

How to connect MySQL database using node js?

Answer»

If you don't install MySQL then you can install MySQL by npm install mysql.

Example CREATE Connection

You can write connection code in a SINGLE file and call in all PAGES where you NEED to interact with database.

var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "your database USERNAME",
password: "database password"
});

con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});

 

34.

What is UUID, and how you can generate it in Node.js?

Answer»

A UUID is a Universal Unique Identifier is a method for generating ids that have been standardized by the Open Software Foundation (OSF).

You can generate UUIDs in Node.js through the node-UUID. It is a speedy and straightforward way of generating VERSION 1 & 4 UUIDs.

Here's how to generate UUIDs
  • Install the node-uuid through the npm manager using npm install uuid.
  • Use it in your script like this:

CONST uuidv1 = require('uuid/v1')
const uuidv4 = require('uuid/v4')
var uuid1 = uuidv1()
var uuid5 = uuidv4()

Here is how your OUTPUT would look. ALTHOUGH, due to the nature of UUIDs, your GENERATED IDs may be completely different.

Output

uuid1 v1 => 6bf958f0-95ed-17e8-sds37-23f5ae311cf6
uuid5 v4 => 356fasda-dad8d-42b7-98b8-a89ab58a645e

 

35.

Explain the difference between const and let in node js?

Answer»
S.noletconst
1.It can be reassigned, but can’t be redeclared in the same scope.It can be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.
2.It is BENEFICIAL to have for the vast MAJORITY of the code. It can significantly ENHANCE your code READABILITY and decrease the chance of a programming error.It is a good practice for both maintainability, readability and avoids using MAGIC literals
36.

How to use Async Await with promises in node js?

Answer»
  • Step1. Install Async first with "npm install async" command
  • Step2. Call the async in your file with you will USE async.
    var async = require("async");
  • Step3. Make an async function and call await function inside async function.
    let phoneChecker = async function (req, res) {
         CONST result = await phoneExistOrNot();
    }
    exports.phoneChecker = phoneChecker;

    await will work only under async function.
    For example: here is " phoneChecker " is async function, and phoneExistOrNot is await service.
  • Step4. Now you can write your logic in await function.
    let phoneExistOrNot = async function (req, res){
        RETURN new Promise(function(resolve, reject) {
            db.query('select name, PHONE from users where phone = 123456789 ', function (error, result) {
                 if(error) {
                     reject(error);
                     console.log('Error');
                 } else {
                      resolve(result);
                      console.log('Success');
                 }
          })
    });
    }
Related Article: How to use async-await in node js
37.

How to pass an array in insert query using node js?

Answer»

The array of records can easily be bulk inserted into the node.js. Before insertion, you have to convert it into an array of arrays.

Example

VAR mysql = require('node-mysql');
var CONN = mysql.createConnection({
     // your database connection
});

var sql = "INSERT INTO Test (name, email) VALUES ?";
var values = [
    ['best interview question', '[email protected]'],
    ['Admin', '[email protected]'],
];

conn.query(sql, [values], FUNCTION(err) {
     if (err) throw err;
     conn.end();
});

38.

What is the difference between readFile vs. createReadStream in Node.js?

Answer»
Pure PipesImpure Pipes
This will thoroughly read the file into the memory before making it available to the user.It will read chunks of a file as per specifications provided by the user.
Since the whole data is sent after it has been loaded, it will take time for the client to reach and hence, is slower.Since it READS files in chunks, the client will read the data FASTER than in readFile.
It is EASIER to CLEAN the non-used memory by Node.js in this.It is much more difficult for Node.js to clean up memory in this case.
It will not scale the requests at a given time, preferably all at once.It will pipe the content directly to the client using HTTP response objects, making it time-saving.

Note: Our aim while creating nodejs interview questions, is to HELP you grow as a Node Developer. The questions mentioned here have been asked by leading organizations during technical rounds of the interview process.

39.

What is callback hell, and how can it be avoided?

Answer»

Callback HELL is a SITUATION in Javascript when you face callbacks within callbacks or nested callbacks.

It looks somewhat like this:

firstFunction(ARGS, function() {
   secondFunction(args, function() {
      thirdFunction(args, function() {
      });
   });
});

There are two significant ways to avoid Callback Hell in NodeJS:

1. Using Promises

const makeBurger = () => {
    return getChicken()
    .then(chicken => cookChicken(chicken))
};
makeBurger().then(burger => serve(burger));

SEE, it is just more easy to read and manage in comparison to the nested callbacks.

2. USE Async/Await

Using Asynchronous functions, we can convert makeBurger into one synchronous code. Also, maybe you can get helpers to getBun and getChicken at the same time, meaning, you can use await with Promise.all. Here's the code:

const makeBurger = async () => {
    const cookedChicken = await cookChicken(chicken);
    return cookedChicken;
};
makeBurger().then(serve);

40.

What is the difference between the node js child process and clusters?

Answer»
Child ProcessClusters
It is a module of Node.js containing sets of properties and functions HELPING developers throughout the forking process.These can be easily SPUN using Node's child_process module and can communicate with each other using a messaging system.
It occurs when you have TWO or more node INSTANCES running with one master process routing.It SPAWNS a new script or executable on the system.
41.

What is the fork in node JS?

Answer»

Fork() is used to spawn a NEW Node.js PROCESS. It invokes a specific MODULE with an IPC COMMUNICATION channel, thus enabling the sending of MESSAGES between a parent and child.

Example

const { fork } = require('child_process');

const forked = fork('child.js');

forked.on('message', (msg) => {
     console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

42.

What are Global objects, and how do you use it in node JS?

Answer»

Global objects are those who provide variables and functions that are available anywhere within the code. By default, they are those objects which are BUILT into the language or the environment.

All the properties of Global Objects can be accessed directly in node.js USING the window.

Example

window.currentUser = {
    name: "BEST Interview QUESTION"
};

43.

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

Answer»

In Node.JS, MODULE.exports is a special OBJECT that is included in every JavaScript file present in the Node.JS file default. Here module is a variable that represents the current module, and export is the object that will be exposed as the module.

Here we export a string from testYourModule.js file

EXAMPLE

// testYourModule.js
module.exports = "Best INTERVIEW QUESTIONS provides an example of module.exports"

// index.js
const params = require('./testYourModule.js')
console.log(params )

44.

What is the command for import external libraries in Node JS?

Answer»

Command “require” is used in NODE JS for IMPORT external libraries. Mentioned below is an EXAMPLE of this. “var http=require (“http”)”. This will load the library and the SINGLE exported object through the HTTP variable.

45.

What is Express js?

Answer»

Express js is a type of framework which is used for node js. It released under the MIT License. It HELPS to manage a server and routes. It is ALSO designed for building WEB applications and APIs.

It was founded by TJ Holowaychuk. The first release of express js was on the 22nd of May, 2010. Version 0.12.0.

Features of Express framework:
  • It can be used to design single-page or multi-page web applications.
  • It helps to setup MIDDLEWARES to respond to HTTP Requests.
  • It helps US to render HTML Pages dynamically.
46.

In Node.js, which framework is used commonly?

Answer»

Hapi.js or Express.js is robust and modular for DEVELOPING the APIS. It has input VALIDATION, configuration FUNCTIONING, and many other FEATURES.

47.

How Node.js and JavaScript are related?

Answer»

Node.js appeared when the engineers of JavaScript expanded it from something you could just keep running in the BROWSER to something you could keep running on your machine as an independent application. The Node run-time environment incorporates all that you have to execute a program written in JavaScript.

25. How do you make node JS secure?

Here are some best PRACTICES to make your NodeJS application secure:

  • Limit the number of concurrent requests through MIDDLEWARE such as cloud firewalls, cloud load balancers, etc.
  • Adjust the HTTP response using secure headers for enhanced SECURITY and blocking vulnerabilities such as XSS, clickjacking, etc.
  • Use a secure hash + salt function such as bcrypt to store passwords, API keys, and secrets INSTEAD of Node.js crypto library.
  • Limit brute-force authorization attacks by limiting the number of failed login attempts and, in such a case, ban the user's IP address.
  • Limit your payload size by using a reverse-proxy or a middleware.
  • Avoid pushing secrets on to the npm registry.
  • Use cookies securely
  • Ensure the security of all your dependencies
48.

How does Passport handle authorization?

Answer»

Passport is an authentication MIDDLEWARE that is extremely flexible and modular. Any APPLICATION might need to incorporate a user's information through third-party services. In this particular case, the application will send out a "CONNECT" request with the user's Twitter or Facebook accounts.

Authorization is handled by calling passport.authorize(). If the authorization is granted, the RESULT by the verify callback shall be assigned to the req.ACCOUNT.

Here's how authorization of a Twitter account is handled in Passport.

Example

app.get('/connect/twitter',
  passport.authorize('twitter-authz', { failureRedirect: '/account' })
);

app.get('/connect/twitter/callback',
  passport.authorize('twitter-authz', { failureRedirect: '/account' }),
  function(req, res) {
    var user = req.user;
    var account = req.account;

    account.userId = user.id;
    account.save(function(err) {
      if (err) { return self.error(err); }
      self.redirect('/');
    });
  }
);

49.

What is the difference between setImmediate() and setTimeout()?

Answer»

setImmediate() executes a script once the CURRENT poll or the event loop phase has completed.

setTimeout() is used to SCHEDULE scripts to be run after a MINIMUM threshold has elapsed.

The order in which these timers are executed varies on the context in which they are used. If both are called from WITHIN the MODULE, timing will be bound by the process performance.

50.

Why we have to keep separate Express app and server?

Answer»

Express APP encapsulates your API logical, which is your data abstraction. This is where you should KEEP up your DB logic or data models.

The server should be differently handled as its sole responsibility is to keep the app/website running. The SEPARATION of concerns will LEAD to optimization.