Google News
logo
NodeJS Interview Questions
Node.js is a powerful framework developed on Chrome’s V8 JavaScript engine that compiles the JavaScript directly into the native machine code. It is a lightweight framework used for creating server-side web applications and extends JavaScript API to offer usual server-side functionalities. It is generally used for large-scale application development, especially for video streaming sites, single page application, and other web applications.
Node.js makes building scalable network programs easy. Some of its advantages include:
 
* It is generally fast
* It almost never blocks
* It offers a unified programming language and data type
* Everything is asynchronous 
* It yields great concurrency
Node.js is a virtual machine that uses JavaScript as its scripting language and runs on a v8 environment. It works on a single-threaded event loop and a non-blocking I/O which provides high rate as it can handle a higher number of concurrent requests. Also, by making use of the ‘HTTP’ module, Node.js can run on any stand-alone web server. 
Node.js uses a single threaded model in order to support async processing. With async processing, an application can perform better and is more scalable under web loads. Thus, Node.js makes use of a single-threaded model approach rather than typical thread-based implementation.
There are two types of API functions in Node.js:
 
* Asynchronous, non-blocking functions
* Synchronous, blocking functions
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.
* 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
Node.js is widely used in the following applications:
 
* Real-time chats
* Internet of Things
* Complex SPAs (Single-Page Applications)
* Real-time collaboration tools
* Streaming applications
* Microservices architecture
NPM stands for Node Package Manager, which is responsible for managing all the packages and modules for Node.js.
 
Node Package Manager provides two main functionalities:
 
* Provides online repositories for node.js packages/modules, which are searchable on search.nodejs.org

* Provides command-line utility to install Node.js packages, and also manages Node.js versions and dependencies
The “require” command is used for importing external libraries. For example:   “var http=require (“http”)”.  This will load the http library and the single exported object through the http variable.
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 already registered with the element executes whenever an event is triggered.
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: 'freetimelearning'});
  myPost.save(function(err,myInstance){
    if(err){
       //handle error and return
     }
      //go ahead with `myInstance`
   });
Some of the reasons why Node.js is preferred include:
 
* Node.js is very fast

* Node Package Manager has over 50,000 bundles available at the developer’s disposal

* Perfect for data-intensive, real-time web applications, as Node.js never waits for an API to return data

* Better synchronization of code between server and client due to same code base

* Easy for web developers to start using Node.js in their projects as it is a JavaScript library
MongoDB is the most common database used with Node.js. It is a NoSQL, cross-platform, document-oriented database that provides high performance, high availability, and easy scalability.
There are two commonly used libraries in Node.js:
 
* ExpressJS - Express is a flexible Node.js web application framework that provides a wide set of features to develop both web and mobile applications.

* Mongoose - Mongoose is also a Node.js web application framework that makes it easy to connect an application to a database.
Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.
REPL stands for (READ, EVAL, PRINT, LOOP). Node js comes with bundled REPL environment. This allows for the easy creation of CLI (Command Line Interface) applications.
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.
Asynchronous literally means not synchronous. We are making HTTP requests which are asynchronous, means we are not waiting for the server response. We continue with other block and respond to the server response when we received.

The term Non-Blocking is widely used with IO. For example non-blocking read/write calls return with whatever they can do and expect caller to execute the call again. Read will wait until it has some data and put calling thread to sleep.
Streams are objects that enable you to read data or write data continuously.
 
There are four types of streams:
 
Readable : Used for reading operations
 
Writable : Used for write operations
 
Duplex : Can be used for both reading and write operations
 
Transform : A type of duplex stream where the output is computed based on input
* All Node.js library APIs are asynchronous, which means they are also non-blocking

* A Node.js-based server never waits for an API to return data. Instead, it moves to the next API after calling it, and a notification mechanism from a Node.js event responds to the server for the previous API call
The control flow function is a piece of code that runs in between several asynchronous function calls.
Buffer class stores raw data similar to an array of integers, but corresponds to a raw memory allocation outside the V8 heap. Buffer class is used because pure JavaScript is not compatible with binary data
Piping is a mechanism used to connect the output of one stream to another stream. It is normally used to retrieve data from one stream, and pass output to another stream
A reactor pattern is a concept of non-blocking I/O operations. This pattern provides a handler that is associated with each I/O operation. As soon as an I/O request is generated, it is then submitted to a demultiplexer
Middleware is a function that receives the request and response objects. Most tasks that the middleware functions perform are:  
 
* Execute any type of code
* Update or modify the request and the response objects
* Finish the request-response cycle
* Invoke the next middleware in the stack
setImmediate() and setTimeout() are similar, but behave in different ways depending on when they are called.

* setImmediate() is designed to execute a script once the current poll (event loop) phase completes.

* setTimeout() schedules a script to be run after a minimum threshold in ms has elapsed.

The order in which the timers are executed will vary depending on the context in which they are called. If both are called from within the main module, then timing will be bound by the performance of the process.
In Node.js, a test pyramid is a figure which explains the proportion of unit tests, integrations tests, and end-to-end tests are required for the fruitful development of a project. The components of a test pyramid are given below:
 
Unit Tests : They test the individual units of code in isolation. They are fast and you might perform a lot of these tests

Integrations Tests : They test the integration among dissimilar units.

End-to-End (E2E) Tests : They test the system as a whole, right from the User Interface to the data store, and back.
Libuv, a support library of Node.js, is used for asynchronous Input/output. While it was initially developed just for Node.js, it now witnesses practice with other systems such as Luvit, Julia, Pyuv and more. Some of the features of Libuv are:
 
* File System Events
* Child Processes
* Full-featured event loop backed
* Asynchronous TCP & UDP sockets
Even though Node.js can help in creating server-side applications, CPU-incentive applications are not the strong suit of Node.js. The CPU-heavy operations pave the way for the blockage of incoming requests and push the thread into critical situations.
Built on top of Node.js, ExpressJS is a JS framework used to manage the flow of information between the routes and server in server-side apps. Being lightweight, flexible and filled with a variety of relevant features, it is apt for mobile and web application development.
Long Term Support or LTS version/releases of Node.js are the releases which receive all the critical fixes, performance step ups and security updates. These versions receive support for at least 1.5 years and have a focus on security and stability of the application.
Assert is used to write tests in Node.js. The feedback is provided only if any of the test cases that are running fails. To test invariants, the module gives you a set of assertion tests. It is used internally by Node.js, but if you use require (‘assert’) code, you will be able to use it in other applications as well.
In Node.js, streams are the collection of data similar to strings and arrays. Moreover, streams are objects through which you can read source data or write destination data continuously. These streams are particularly helpful for reading and processing large amounts of information. There are four types of streams in Node.js, which are:
 
Readable : Used to read large amount of data from source

Writeable : Used to write data to destination

Duplex : Used for both read and write

Transform : A duplex stream used for data modification
A timer module containing multiple functions for the execution of the code after a specific time period is provided by Node.js. Some of the functions provided in this module are:
 
process.nextTick : This function schedules a callback function which is required to be invoked in the next iteration of the event loop

setTimeout/clearTimeout : This function schedules code execution after the assigned amount of time (in milliseconds)

setImmediate/clearImmediate : This functions executes code at the conclusion of the existing event loop cycle

setInterval/clearInterval : This function is used to execute a block of code a number of times
Both process.nextTick() and setImmediate() are functions of the Timers module, but the difference lies in their execution.
 
The process.nextTick() function waits for the execution of action till the next pass around in the event loop or when the event loop culminates, then only the callback function is invoked.

The setImmediate() function is used for callback method execution on the next cycle of the event loop, which returns it to the event loop for the execution of the input/output operations.
A built-in TCP protocol and the debugging client is provided by Node.js. If you wish to debug your file, you can use the following argument before the name of your JS file which you wish to debug.
node debug [script.js | -e “script” | :]
Following code snippet can be used to make a Post Request in Node.js.
var request = require('request');
request.post(
'http://www.example.com/action',
{ form: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
The one common trait between Node.js, AJAX, and jQuery is that all of them are the advanced implementation of JavaScript. However, they serve completely different purposes.
 
Node.js : It is a server-side platform for developing client-server applications. For example, if we’ve to build an online employee management system, then we won’t do it using client-side JS. But the Node.js can certainly do it as it runs on a server similar to Apache, Django not in a browser.
 
AJAX (aka Asynchronous Javascript and XML) : It is a client-side scripting technique, primarily designed for rendering the contents of a page without refreshing it. There are a no. of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.
 
jQuery : It is a famous JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development. However, it’s not mandatory to use it but as it also manages cross-browser compatibility, so can help you produce highly maintainable web applications.
Events module in Node.js allows us to create and handle custom events. The Event module contains “EventEmitter” class which can be used to raise and handle custom events. It is accessible via the following code.
 
// Import events module
var events = require('events');
 
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

When an EventEmitter instance encounters an error, it emits an “error” event. When a new listener gets added, it fires a “newListener” event and when a listener gets removed, it fires a “removeListener” event.
 
EventEmitter provides multiple properties like “on” and “emit”. The “on” property is used to bind a function to the event and “emit” is used to fire an event.
Yes, Node.js would run on a multi-core system without any issue. But it is by default a single-threaded application, so it can’t completely utilize the multi-core system.
 
However, Node.js can facilitate deployment on multi-core systems where it does use the additional hardware. It packages with a Cluster module which is capable of starting multiple Node.js worker processes that will share the same port.
It’s an approach to connect the output of one stream to the input of another stream, thus creating a chain of multiple stream operations.
Exit codes in Node.js are a specific group of codes that finish off processes, which can include global objects as well. Some of the exit codes in Node.js are:
 
* Internal JavaScript Evaluation Failure
* Fatal Error
* Internal Exception handler Run-time failure
* Unused
* Uncaught fatal exception
When any Node.js project is in the stage of production, Node.js promotes the principle to use NODE_ENV variable to flag it. When the NODE-ENV is set to production, your application will perform at a speed 2 to 3 times faster than usual. The variable also improves judgment during the development phase of projects.
Punycode can be defined as an encoding syntax in Node.js which is helpful for converting the Unicode string of characters into ASCII. This is done as the hostnames can only comprehend ASCII codes and not Unicode. While it was bundled up within the default package in recent versions, you can use it in the previous version using the following code:
 
punycode = require(‘punycode’);
In Node.js, spawn () launches a new process with the available set of commands. This doesn’t generate a new V8 instance only a single copy of the node module is active on the processor. This method can be used when your child process returns a large amount of data to the node.
 
On the other hand, fork () is a particular case of spawn () which generates a new V8 engines instance. Through this method, multiple workers run on a single node code base for multiple tasks.
Node provides a single thread to programmers so that code can be written easily and without bottleneck. Node internally uses multiple POSIX threads for various I/O operations such as File, DNS, Network calls etc.
 
When Node gets I/O request it creates or uses a thread to perform that I/O operation and once the operation is done, it pushes the result to the event queue. On each such event, event loop runs and checks the queue and if the execution stack of Node is empty then it adds the queue result to execution stack.
 
This is how Node manages concurrency.
Tracing is a methodology used to collect all of the tracing information that gets generated by V8, the node core, and the userspace code. All of these are dumped into a log file and are very useful to validate and check the integrity of the information being passed.
readFile : This is used to read all of the contents of a given file in an asynchronous manner. All of the content will be read into the memory before users can access it.

create ReadStream : This is used to break up the field into smaller chunks and then read it. The default chunk size is 64 KB, and this can be changed as per requirement.
The crypto module in Node.js is used to provide users with cryptographic functionalities. This provides them with a large number of wrappers to perform various operations such as cipher, decipher, signing, and hashing operations.
Passport is a widely used middleware present in Node.js. It is primarily used for authentication, and it can easily fit into any Express.js-based web application.
 
With every application created, it will require unique authentication mechanisms. This is provided as single modules by using passport, and it becomes easy to assign strategies to applications based on requirements, thereby avoiding any sort of dependencies.
The DNS lookup method uses a web address for its parameter and returns the IPv4 or IPv6 record, correspondingly.
 
There are other parameters such as the options that are used to set the input as an integer or an object. If nothing is provided here, both IPv4 and IPv6 are considered. The third parameter is for the callback function.
 
The syntax is:
 
dns.lookup(address, options, callback)
Test pyramids are implemented by defining the HTML API. This is done using the following:
 
* A higher number of unit test cases
* A smaller number of integration test methods
* A fewer number of HTTP endpoint test cases
Assert is used to explicitly write test cases to verify the working of a piece of code. The following code snippet denotes the usage of assert:
var assert = require('assert');
function add(x, y) {
return x + y;
}
var result = add(3,5);
assert( result === 8, 'three summed with five is eight');
Advertisement