Node js interview question set 1/Node JS Interview Questions and Answers for Freshers & Experienced

How does Node.js handle the child threads?

In general, Node.js is a single threaded process and doesn’t expose the child threads or thread management methods. But you can still make use of the child threads using spawn() for some specific asynchronous I/O tasks which execute in the background and don’t usually execute any JS code or hinder with the main event loop in the application. If you still want to use the threading concept in your application you have to include a module called ChildProcess explicitly.

Explain the usage of a buffer class in Node.js?

Buffer class in Node.js is used for storing the raw data in a similar manner of an array of integers. But it corresponds to a raw memory allocation that is located outside the V8 heap. It is a global class that is easily accessible can be accessed in an application without importing a buffer module. Buffer class is used because pure JavaScript is not compatible with binary data. So, when dealing with TCP streams or the file system, it’s necessary to handle octet streams.

Differentiate between process.nextTick() and setImmediate()?

In Node.js, process.nextTick() and setImmediate(), both are functions of the Timers module which help in executing the code after a predefined period of time. But these functions differ in their execution. The process.nextTick function waits for the execution of action till the next pass around in the event loop or once the event loop is completed only then it will invoke the callback function. On the other hand, setImmediate() is used to execute a callback method on the next cycle of the event loop which eventually returns it to the event loop in order to execute the I/O operations.

What are the pros and cons of Node.js?

Pros:

If your application does not have any CPU intensive computation, you can build it in Javascript top to bottom, even down to the database level if you use JSON storage object DB like MongoDB.
Crawlers receive a full-rendered HTML response, which is far more SEO friendly rather than a single page application or a websockets app run on top of Node.js.


Cons:

Any intensive CPU computation will block node.js responsiveness, so a threaded platform is a better approach.
Using relational database with Node.js is considered less favourable.

Explain the concept of stub in Node.js.

In Node.js, stubs are basically the programs or functions that are used for stimulating the module or component behavior. During any test cases, stubs provide the canned answers of the functions.

Why node.js is quickly gaining attention from JAVA programmers?

Node.js is quickly gaining attention as it is a loop based server for JavaScript. Node.js gives user the ability to write the JavaScript on the server, which has access to things like HTTP stack, file I/O, TCP and databases.

What do you understand by global objects in Node.js?

In Node.js, Globals are the objects which are global in nature and are available in all the modules of the application. You can use these objects directly in your application, rather than having to include them explicitly. The global objects can be modules, functions, strings, object, etc. Moreover, some of these objects can be in the module scope instead of global scope.

List down the two arguments that async.queue takes as input?

Below are the two arguments that async.queue takes as input:

1. Task Function
2. Concurrency Value

What does event-driven programming mean?

An event-driven programming approach uses events to trigger various functions. An event can be anything, such as typing a key or clicking a mouse button. A call-back function is already registered with the element executes whenever an event is triggered.

For Node.js, why Google uses V8 engine?

Google uses V8 as it is a Chrome runtime engine that converts JavaScript code into native machine code. This, in turn, speeds up the application execution and response process and give you a fast running application.

What do you understand by ESLint?

ESLint is an open source project initially developed by Nicholas C. Zakas in 2013 which aims to provide a linting utility for JavaScript through a plug. Linters in Node.js are good tools for searching certain bug classes, especially those which are related to the variable scope.

Explain libuv.

Libuv is a multi-platform support library of Node.js which majorly is used for asynchronous I/O. It was primarily developed for Node.js, with time it is popularly practiced with other systems like as Luvit, pyuv, Julia, etc. Libuv is basically an abstraction around libev/ IOCP depending on the platform, providing users an API based on libev. A few of the important features of libuv are:

Full-featured event loop backed
File system events
Asynchronous file & file system operations
Asynchronous TCP & UDP sockets
Child processes

What do you understand by callback hell?

Callback Hell is also known as the Pyramid of Doom. It is a pattern caused by intensively nested callbacks which are unreadable and unwieldy. It typically contains multiple nested callback functions which in turn make the code hard to read and debug. It is caused by improper implementation of the asynchronous logic.

async_A(function(){
async_B(function(){
async_C(function(){
async_D(function(){
....
});
});
});
});

List down the major security implementations within Node.js?

Major security implementations in Node.js are:

1. Authentications
2. Error Handling

What are LTS releases of Node.js?

LTS stands Long Term Support version of Node.js that receives all the critical bug fixes along with security updates and performance improvements. These versions are supported for at least 18 months and mainly focus on stability and security. The modifications done to the LTS versions are restricted to the bug fixes, security upgrade, npm, and documentation updates, performance improvement, etc.

What do you understand by Reactor Pattern in Node.js?

Reactor Pattern in Node.js is basically a concept of non-blocking I/O operations. This pattern provides a handler that is associated with each I/O operation and as soon as an I/O request is generated, it is then submitted to a demultiplexer. This demultiplexer is a notification interface which is capable of handling concurrency in non-blocking I/O mode. It also helps in collecting each and every request in the form of an event and then place each event in a queue. Thus resulting in the generation of the Event Queue. Simultaneously, we have our event loop which iterates the events present in the Event Queue.

Explain the purpose of module.exports?

A module in Node.js is used to encapsulate all the related codes into a single unit of code which can be interpreted by shifting all related functions into a single file. For example, suppose you have a file called greet.js that contains the two functions as shown below:

module.exports = {
greetInHindi: function(){
return "NAMASTE";
},
greetInKorean: function(){
return "ANNYEONGHASEYO";
}};
As you can see module.exports provide two functions which can be imported in another file using below code:

var eduGreets = require ("./greet.js");
eduGreets.greetInHindi() //NAMASTE
eduGreets.greetInKorean() //ANNYEONGHASEYO

What is an error-first callback in Node.js?

Error-first callbacks in Node.js are used to pass errors and data. The very first parameter you need to pass to these functions has to be an error object while the other parameters represent the associated data. Thus you can pass the error object for checking if anything is wrong and handle it. In case there is no issue, you can just go ahead and with the subsequent arguments.

var myPost = new Post({title: 'edureka'});
myPost.save(function(err,myInstance){
if(err){
//handle error and return
}
//go ahead with `myInstance`
});

List down the steps using which “Control Flow” controls the function calls in Node.js?

1. Control the order of execution
2. Collect data
3. Limit concurrency
4. Call the next step in the program

Does node run on windows?

Yes – it does. Download the MSI installer from https://nodejs.org/download/

List down the tasks which should be done asynchronously using the event loop?

Below is the list of the tasks which must be done asynchronously using the event loop:

<> I/O operations
<> Heavy computation
<> Anything requiring blocking

Explain REPL in the context of Node.js.

REPL in Node.js stands for Read, Eval, Print, and Loop. It represents a computer environment such as a window console or Unix/Linux shell where any command can be entered and then the system can respond with an output. Node.js comes bundled with a REPL environment by default. REPL can perform the below-listed tasks:

<> Read: Reads the user’s input, parses it into JavaScript data-structure and then stores it in the memory.
<> Eval: Receives and evaluates the data structure.
<> Print: Prints the final result.
<> Loop: Loops the provided command until CTRL+C is pressed twice.

What do you understand by Event-driven programming?

Event-driven programming is an approach that heavily makes use of events for triggering various functions. An event can be anything like a mouse click, key press, etc. When an event occurs, a call back function is executed that is already registered with the element. This approach mainly follows the publish-subscribe pattern. Because of event-driven programming, Node.js is faster when compared to other technologies.

What is the meaning of a test pyramid?

A test pyramid is a methodology that is used to denote the number of test cases executed in unit testing, integration testing, and combined testing (in that order). This is maintained to ensure that an ample number of test cases are executed for the end-to-end development of a project.

What are some of the most commonly used libraries in Node.js?

There are two commonly used libraries in Node.js:

a) ExpressJS - Express is a flexible Node.js web application framework that provides a wide set of features to develop web and mobile applications.
b) Mongoose - Mongoose is also a Node.js web application framework that makes it easy to connect an application to a database.

What is Event loop in Node.js work? And How does it work?

The Event loop handles all async callbacks. Node.js (or JavaScript) is a single-threaded, event-driven language. This means that we can attach listeners to events, and when a said event fires, the listener executes the callback we provided.

Whenever we are call setTimeout, http.get and fs.readFile, Node.js runs this operations and further continue to run other code without waiting for the output. When the operation is finished, it receives the output and runs our callback function.

So all the callback functions are queued in an loop, and will run one-by-one when the response has been received.

How can you import external libraries into Node.js?

External libraries can be easily imported into Node.js using the following command:

var http=require (“http”)
This command will ensure that the HTTP library is loaded completely, along with the exported object.

Next among the Node JS questions, you need to know about event-driven programming.

What is the primary reason to use the event-based model in Node.js?

The event-based model in Node.js is used to overcome the problems that occur when using blocking operations in the I/O channel.

Next in this blog comprising Node.js questions, you need to understand how you can import libraries into Node.js.

Are there any disadvantages to using Node.js?

A multi-threaded platform can run more effectively and provide better responsiveness when it comes to the execution of intensive CPU computation, and the usage of relational databases with Node.js is becoming obsolete already.

What is the use of DNS module in Node.js?

DNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup. No need for memorising IP addresses – DNS servers provide a nifty solution of converting domain or subdomain names to IP addresses.

What is EventEmitter in Node.js?

All objects that emit events are members of EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. All values returned by the called listeners are ignored and will be discarded.

What is REPL? What purpose it is used for?

REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL environment when it is installed. System interacts with the user through outputs of commands/expressions used. It is useful in writing and debugging the codes. The work of REPL can be understood from its full form:

1. Read: It reads the inputs from users and parses it into JavaScript data structure. It is then stored to memory.
2. Eval: The parsed JavaScript data structure is evaluated for the results.
3. Print: The result is printed after the evaluation.
4. Loop: Loops the input command. To come out of NODE REPL, press ctrl+c twice

How can you make sure your dependencies are safe?

The only option is to automate the update / security audit of your dependencies. For that there are free and paid options:

1. npm outdated
2. Trace by RisingStack
3. NSP
4. GreenKeeper
5. Snyk
6. npm audit
7. npm audit fix

How can you secure your HTTP cookies against XSS attacks?

1. When the web server sets cookies, it can provide some additional attributes to make sure the cookies won't be accessible by using malicious JavaScript. One such attribute is HttpOnly.

Set-Cookie: [name]=[value]; HttpOnly
HttpOnly makes sure the cookies will be submitted only to the domain they originated from.

2. The "Secure" attribute can make sure the cookies are sent over secured channel only.

Set-Cookie: [name]=[value]; Secure
3. The web server can use X-XSS-Protection response header to make sure pages do not load when they detect reflected cross-site scripting (XSS) attacks.

X-XSS-Protection: 1; mode=block
4. The web server can use HTTP Content-Security-Policy response header to control what resources a user agent is allowed to load for a certain page. It can help to prevent various types of attacks like Cross Site Scripting (XSS) and data injection attacks.

Content-Security-Policy: default-src 'self' *.http://sometrustedwebsite.com

What is a stub?

Stubbing and verification for node.js tests. Enables you to validate and override behaviour of nested pieces of code such as methods, require() and npm modules or even instances of classes. This library is inspired on node-gently, MockJS and mock-require.

Features of Stub:

1. Produces simple, lightweight Objects capable of extending down their tree
2. Compatible with Nodejs
3. Easily extendable directly or through an ExtensionManager
4. Comes with predefined, usable extensions
Stubs are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called.

When should you npm and when yarn?

npm
It is the default method for managing packages in the Node.js runtime environment. It relies upon a command line client and a database made up of public and premium packages known as the the npm registry. Users can access the registry via the client and browse the many packages available through the npm website. Both npm and its registry are managed by npm, Inc.

node -v
npm -v

Yarn
Yarn was developed by Facebook in attempt to resolve some of npm’s shortcomings. Yarn isn’t technically a replacement for npm since it relies on modules from the npm registry. Think of Yarn as a new installer that still relies upon the same npm structure. The registry itself hasn’t changed, but the installation method is different. Since Yarn gives you access to the same packages as npm, moving from npm to Yarn doesn’t require you to make any changes to your workflow.

npm install yarn --global

What are Promises in Node.js?

It allows to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future.

Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).

The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:

1. pending - The initial state of a promise.
2. fulfilled - The state of a promise representing a successful operation.
3. rejected - The state of a promise representing a failed operation. Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).


Creating a Promise

var myPromise = new Promise(function(resolve, reject){
....
})

What is an event loop in Node.js?

When running an application, callbacks are entities that have to be handled. In the case of Node.js, event loops are used for this purpose. Since Node.js supports the non-blocking send, this is a very important feature to have.

The working of an event loop begins with the occurrence of a callback wherever an event begins. This is usually run by a specific listener. Node.js will keep executing the code after the functions have been called, without expecting the output prior to the beginning.

Once, all of the code is executed, outputs are obtained and the callback function is executed. This works in the form of a continuous loop, hence the name event loop.

Why is Node.js so popular these days?

Node.js has gained an immense amount of traction as it mainly uses JavaScript. It provides programmers with the following options:

a) Writing JavaScript on the server
b) Access to the HTTP stack
c) File I/O entities
d) TCP and other protocols
e) Direct database access

What is the control flow function?

The control flow function is a common code snippet, which executes whenever there are any asynchronous function calls made, and they are used to evaluate the order in which these functions are executed in Node.js.

What is the difference between synchronous and asynchronous functions?

Synchronous functions are mainly used for I/O operations. They are instantaneous in providing a response to the data movement in the server and keep up with the data as per the requirement. If there are no responses, then the API will throw an error.

On the other hand, asynchronous functions, as the name suggests, work on the basis of not being synchronous. Here, HTTP requests when pushed will not wait for a response to begin. Responses to any previous requests will be continuous even if the server has already got the response.

What are the different API functions supported by Node.js?

There are two types of API functions. They are as follows:

a) Synchronous APIs: Used for non-blocking functions
b) Asynchronous APIs: Used for blocking functions

Briefly explain the working of Node.js.

Node.js is an entity that runs in a virtual environment, using JavaScript as the primary scripting language. It uses a simple V8 environment to run on, which helps in the provision of features like the non-blocking I/O and a single-threaded event loop.

How is Node.js most frequently used?

Node.js is widely used in the following applications:

1. Real-time chats
2. Internet of Things
3. Complex SPAs (Single-Page Applications)
4. Real-time collaboration tools
5. Streaming applications
6. Microservices architecture

How would you define the term I/O?

The term I/O is used to describe any program, operation, or device that transfers data to or from a medium and to or from another medium


Every transfer is an output from one medium and an input into another. The medium can be a physical device, network, or files within a system

Explain callback in Node.js.

A callback function is called after a given task. It allows other code to be run in the meantime and prevents any blocking. Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks.

Why is Node.js Single-threaded?

Node.js is single-threaded for async processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved instead of the typical thread-based implementation.

How does Node.js work?

A web server using Node.js typically has a workflow that is quite similar to the diagram illustrated below. Let’s explore this flow of operations in detail.

1. Clients send requests to the webserver to interact with the web application. Requests can be non-blocking or blocking:
2. Querying for data
3. Deleting data
4. Updating the data
5. Node.js retrieves the incoming requests and adds those to the Event Queue
6. The requests are then passed one-by-one through the Event Loop. It checks if the requests are simple enough not to require any external resources
7. The Event Loop processes simple requests (non-blocking operations), such as I/O Polling, and returns the responses to the corresponding clients
A single thread from the Thread Pool is assigned to a single complex request. This thread is responsible for completing a particular blocking request by accessing external resources, such as computation, database, file system, etc.

Once the task is carried out completely, the response is sent to the Event Loop that sends that response back to the client.

Why use Node.js?

Node.js makes building scalable network programs easy. Some of its advantages include:

1. It is generally fast
2. It rarely blocks
3. It offers a unified programming language and data type
4. Everything is asynchronous
5. It yields great concurrency

What is Node.js? Where can you use it?

Node.js is an open-source, cross-platform JavaScript runtime environment and library to run web applications outside the client’s browser. It is used to create server-side web applications.

Node.js is perfect for data-intensive applications as it uses an asynchronous, event-driven model. You can use I/O intensive web applications like video streaming sites. You can also use it for developing: Real-time web applications, Network applications, General-purpose applications, and Distributed systems.

Search
R4R Team
R4R provides Node JS Freshers questions and answers (Node JS Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,Node js interview question set 1,Node JS Freshers & Experienced Interview Questions and Answers,Node JS Objetive choice questions and answers,Node JS Multiple choice questions and answers,Node JS objective, Node JS questions , Node JS answers,Node JS MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for Node JS fresher interview questions ,Node JS Experienced interview questions,Node JS fresher interview questions and answers ,Node JS Experienced interview questions and answers,tricky Node JS queries for interview pdf,complex Node JS for practice with answers,Node JS for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .