Top Node JS Interview Questions and Answers

Last updated on Feb 18 2022
Manohar Sharma

Table of Contents

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.

Why use Node.js?

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

  • It is generally fast
  • It rarely blocks
  • It offers a unified programming language and data type
  • Everything is asynchronous
  • It yields great concurrency

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.

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.

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.

a1 6

  • Clients send requests to the webserver to interact with the web application. Requests can be non-blocking or blocking:
  • Querying for data
  • Deleting data
  • Updating the data
  • Node.js retrieves the incoming requests and adds those to the Event Queue
  • 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
  • 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.

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

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

Explain the difference between frontend and backend development?

Front-end Back-end
Frontend refers to the client-side of an application Backend refers to the server-side of an application
It is the part of a web application that users can see and interact with It constitutes everything that happens behind the scenes
It typically includes everything that attributes to the visual aspects of a web application It generally includes a web server that communicates with a database to serve requests
HTML, CSS, JavaScript, AngularJS, and ReactJS are some of the essentials of frontend development Java, PHP, Python, and Node.js are some of the backend development technologies

What is NPM?

NPM stands for Node Package Manager, 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

What are the modules in Node.js?

Modules are like JavaScript libraries that can be used in a Node.js application to include a set of functions. To include a module in a Node.js application, use the require() function with the parentheses containing the module’s name.

a2 6

Node.js has many modules to provide the basic functionality needed for a web application. Some of them include:

Core Modules Description
HTTP Includes classes, methods, and events to create a Node.js HTTP server
util Includes utility functions useful for developers
fs Includes events, classes, and methods to deal with file I/O operations
url Includes methods for URL parsing
query string Includes methods to work with query string
stream Includes methods to handle streaming data
zlib Includes methods to compress or decompress files

Why is Node.js preferred over other backend technologies like Java and PHP?

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

What is the difference between Angular and Node.js?

Angular Node.js
It is a frontend development framework It is a server-side environment
It is written in TypeScript It is written in C, C++ languages
Used for building single-page, client-side web applications Used for building fast and scalable server-side networking applications
Splits a web application into MVC components Generates database queries

Which database is more popularly used with Node.js?

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.

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

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 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.

What are the pros and cons of Node.js?

Node.js Pros Node.js Cons
Fast processing and an event-based model Not suitable for heavy computational tasks
Uses JavaScript, which is well-known amongst developers Using callback is complex since you end up with several nested callbacks
Node Package Manager has over 50,000 packages that provide the functionality to an application Dealing with relational databases is not a good option for Node.js
Best suited for streaming huge amounts of data and I/O intensive operations Since Node.js is single-threaded, CPU intensive tasks are not its strong suit

What is the command used to import external libraries?

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.

Now that we have covered some of the important beginner-level Node.js interview questions let us look at some of the intermediate level Node.js interview questions.

a3 7

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.

What is an Event Loop in Node.js?

Event loops handle asynchronous callbacks in Node.js. It is the foundation of the non-blocking input/output in Node.js, making it one of the most important environmental features.

What is an EventEmitter in Node.js?

  • EventEmitter is a class that holds all the objects that can emit events
  • Whenever an object from the EventEmitter class throws an event, all attached functions are called upon synchronously

a4 5

What are the two types of API functions in Node.js?

The two types of API functions in Node.js are:

  • Asynchronous, non-blocking functions
  • Synchronous, blocking functions

What is the package.json file?

The package.json file is the heart of a Node.js system. This file holds the metadata for a particular project. The package.json file is found in the root directory of any Node application or module

This is what a package.json file looks like immediately after creating a Node.js project using the command:  npm init

You can edit the parameters when you create a Node.js project.

a5 5

How would you use a URL module in Node.js?

The URL module in Node.js provides various utilities for URL resolution and parsing. It is a built-in module that helps split up the web address into a readable format.

a6 5

What is the Express.js package?

Express is a flexible Node.js web application framework that provides a wide set of features to develop both web and mobile applications

How do you create a simple Express.js application?

  • The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on
  • The response object represents the HTTP response that an Express app sends when it receives an HTTP request

a7 5

What are streams in Node.js?

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

How do you install, update, and delete a dependency?

a8 5

How do you create a simple server in Node.js that returns Hello World?

a9 3

  • Import the HTTP module
  • Use createServer function with a callback function using request and response as parameters.
  • Type “hello world.”
  • Set the server to listen to port 8080 and assign an IP address

Explain asynchronous and non-blocking APIs in Node.js.

  • 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

How do we implement async in Node.js?

As shown below, the async code asks the JavaScript engine running the code to wait for the request.get() function to complete before moving on to the next line for execution.

a10 1

What is 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. You can export a module using the module.exports, which allows it to be imported into another file using a required keyword.

What is a callback function in Node.js?

A callback is a function called after a given task. This prevents any blocking and enables other code to run in the meantime.

In the last section, we will now cover some of the advanced-level Node.js interview questions.

What is REPL in Node.js?

REPL stands for Read Eval Print Loop, and it represents a computer environment. It’s similar to a Windows console or Unix/Linux shell in which a command is entered. Then, the system responds with an output

a11 1

What is the control flow function?

The control flow function is a piece of code that runs in between several asynchronous function calls.

How does control flow manage the function calls?

a12 1

What is the difference between fork() and spawn() methods in Node.js?

fork() spawn()
1 1 2 1
fork() is a particular case of spawn() that generates a new instance of a V8 engine. Spawn() launches a new process with the available set of commands.
Multiple workers run on a single node code base for multiple tasks. This method doesn’t generate a new V8 instance, and only a single copy of the node module is active on the processor.

What is the buffer class in Node.js?

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

What is piping in Node.js?

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

What are some of the flags used in the read/write operations in files?

a13 1

How do you open a file in Node.js?

a14 1

What is callback hell?

  • Callback hell, also known as the pyramid of doom, is the result of intensively nested, unreadable, and unmanageable callbacks, which in turn makes the code harder to read and debug
  • improper implementation of the asynchronous logic causes callback hell

What is a reactor pattern in Node.js?

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

What is a test pyramid in Node.js?

a15 1

Describe Node.js exit codes.

a16 1

Explain the concept of middleware in Node.js.

Middleware is a function that receives the request and response objects. Most tasks that the middleware functions perform are:

  • Execute any code
  • Update or modify the request and the response objects
  • Finish the request-response cycle
  • Invoke the next middleware in the stack

What are the different types of HTTP requests?

HTTP defines a set of request methods used to perform desired actions. The request methods include:

GET:  Used to retrieve the data

POST:  Generally used to make a change in state or reactions on the server

HEAD: Similar to the GET method, but asks for the response without the response body

DELETE:  Used to delete the predetermined resource

How would you connect a MongoDB database to Node.js?

To create a database in MongoDB:

  • Start by creating a MongoClient object
  • Specify a connection URL with the correct IP address and the name of the database you want to create

a17 1

What is the purpose of NODE_ENV?

a18 1

List the various Node.js timing features.

As you prepare for your upcoming job interview, we hope that this comprehensive guide has provided more insight into what types of questions you’ll be asked.

a19 1

What is node.js?

Node.js is a Server side scripting which is used to build scalable programs. Its multiple advantages over other server side languages, the prominent being non-blocking I/O.

How node.js works?

Node.js works on a v8 environment, it is a virtual machine that utilizes JavaScript as its scripting language and achieves high output via non-blocking I/O and single threaded event loop.

What do you mean by the term I/O ?

I/O is the shorthand for input and output, and it will access anything outside of your application. It will be loaded into the machine memory to run the program, once the application is started.

Explain the purpose of module.exports.

The purpose is to give instructions to tell Node.js about which part of the code like objects, functions, strings etc. should be exported from a given file so that other files can access it. Suppose we have a module that looks like:

{
   id: '.',
   exports: {},
   parent: null,
   filename: '/modtest.js',
   loaded: false,
   children: [],
   paths:
   [
       '/node_modules',
       '/Users/node_modules',
       '/Users/mycomp/projects/node_modules',
       '/node_modules'
   ]
}

Note that the exports property is empty, now if we apply code to this property, that will become the export of the module. If we require the module in another file, that will be the export property value:

module.exports.stringProperty = "Hello, welcome";
console.log(module);
{
      id: '.',
      exports: { stringProperty: 'Hello, welcome' }
       ...
}

What is the Reactor Pattern in Node.js?

It is a concept of non-blocking I/O operations in Node.js. Through this pattern, we get the handler (or callback function) for each I/O operation. Each I/O request is submitted to a demultiplexer, that handles concurrency and queues the requests/events. Reactor pattern consists of resources, event notifier/demultiplexer, event loop, event queue, request handler.

Explain LTS releases of Node.js

LTS or Long-Term Support is applied to release lines that are supported and maintained by Node.js project for an extended period. There are two types of LTS:

  1. Active, which is actively maintained and upgraded, and
  2. maintenance line that is nearing its end of the line and is maintained for a short window of time.

What is a URL module?

The URL module provides APIs to work with URLs:

  • a legacy API which is specific to Node.js.
  • newer API that implements WHATWG URL Standard used by web browsers.

Some example methods are URL.port, URL.password, URL.host, url.toString() under the URL class. For the full documentation, check the official URL module page.

Explain the working mechanism of control flow function?

Control flow function is the sequence in which statements or functions are executed. Since I/O operations are non-blocking in Node.js, control flow cannot be linear. Therefore, it registers a callback to the event loop and passes the control back to the node, so that the next lines of code can run without interruption. For example:
[code language=”javascript”]

fs.readFile('/root/text.txt', func(err, data){
console.log(data);
});
console.log("This is displayed first");
[/code]

In this, the readFile operation will take some time; however, the next console.log is not blocked. Once the operation completes, data will be displayed.

What does event-driven programming mean?

In computer programming, event driven programming is a programming paradigm in which the flow of the program is determined by events like messages from other programs or threads. It is an application architecture technique divided into two sections 1) Event Selection 2) Event Handling.

Where can we use node.js?

Node.js can be used for the following purposes.

  • Web applications ( especially real-time web apps )
  • Network applications
  • Distributed systems
  • General purpose applications

What is the advantage of using node.js?

  • It provides an easy way to build scalable network programs
  • Generally fast
  • Great concurrency
  • Asynchronous everything
  • Almost never blocks

What are the two types of API functions in Node.js ?

The two types of API functions in Node.js are

  • Asynchronous, non-blocking functions
  • Synchronous, blocking functions

What is control flow function?

A generic piece of code which runs in between several asynchronous function calls is known as control flow function.

Explain the steps how “Control Flow” controls the functions calls?

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

Why Node.js is single threaded?

For async processing, Node.js was created explicitly as an experiment. It is believed that more performance and scalability can be achieved by doing async processing on a single thread under typical web loads than the typical thread based implementation.

Does node run on windows?

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

Can you access DOM in node?

No, you cannot access DOM in node.

Using the event loop what are the tasks that should be done asynchronously?

  • I/O operations
  • Heavy computation
  • Anything requiring blocking

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 are the two arguments that async.queue takes?

The two arguments that async.queue takes

  • Task function
  • Concurrency value

What is an event loop in Node.js ?

To process and handle external events and to convert them into callback invocations an event loop is used. So, at I/O calls, node.js can switch from one request to another.

Mention the steps by which you can async in Node.js?

By following steps you can async Node.js

  • First class functions
  • Function composition
  • Callback Counters
  • Event loops

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.

How Node.js overcomes the problem of blocking of I/O operations?

Node.js solves this problem by putting the event based model at its core, using an event loop instead of threads.

What is the difference between Node.js vs Ajax?

The difference between Node.js and Ajax is that, Ajax (short for Asynchronous Javascript and XML) is a client side technology, often used for updating the contents of the page without refreshing it. While,Node.js is Server Side Javascript, used for developing server software. Node.js does not execute in the browser but by the server.

What are the Challenges with Node.js ?

Emphasizing on the technical side, it’s a bit of challenge in Node.js to have one process with one thread to scale up on multi core server.

What does it mean “non-blocking” in node.js?

In node.js “non-blocking” means that its IO is non-blocking.  Node uses “libuv” to handle its IO in a platform-agnostic way. On windows, it uses completion ports for unix it uses epoll or kqueue etc. So, it makes a non-blocking request and upon a request, it queues it within the event loop which call the JavaScript ‘callback’ on the main JavaScript thread.

What is the command that is used in node.js to import external libraries?

Command “require” 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.

Mention the framework most commonly used in node.js?

“Express” is the most common framework used in node.js.

What is ‘Callback’ in node.js?

Callback function is used in node.js to deal with multiple requests made to the server. Like if you have a large file which is going to take a long time for a server to read and if you don’t want a server to get engage in reading that large file while dealing with other requests, call back function is used. Call back function allows the server to deal with pending request first and call a function when it is finished.

Differentiate between JavaScript and Node.js.

JavaScript vs Node.js
Features JavaScript Node.js
Type Programming Language Interpreter and environment for JavaScript
Utility Used for any client-side activity for a web application Used for accessing or performing any non-blocking operation of any operating system
Running Engine Spider monkey (FireFox), JavaScript Core (Safari), V8 (Google Chrome), etc. V8 (Google Chrome)

What Is Node.js?

Node.js is an extremely 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.

List down the major benefits of using Node.js?

Features Description
Fast Node.js is built on Google Chrome’s V8 JavaScript Engine which makes its library very fast in code execution
Asynchronous Node.js based server never waits for an API to return data thus making it asynchronous
Scalable It is highly scalable because of its event mechanism which helps the server to respond in a non-blocking way
Open Source Node.js has an extensive open source community which has contributed in producing some excellent modules to add additional capabilities to Node.js applications
No Buffering Node.js applications simply output the data in chunks and never buffer any data

What is the difference between Angular and Node.js?

Angular Node.js
1. It is an open-source web application development framework 1. It is a cross-platform run-time environment for applications
2. It is written in TypeScript 2. It is written in C, C++ and JavaScript languages
3. Used for building single-page client-side web applications 3. Used for building fast and scalable server-side networking applications
4. Angular itself is aweb application framework 4. Node.js has many different frameworks like Sails.js, Partial.js, and Express.js, etc.
5. Ideal for creating highly active and interactive web apps 5. Ideal for developing small size projects
6. Helpful in splitting an app into MVC components 6. Helpful in generating database queries
7. Suitable for developing real-time applications 7. Suitable in situations where something faster and more scalable is required

Why Node.js is single threaded?

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.

How do Node.js works?

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.

Where Node.js can be used?

Node.js can be used to develop:

  • Real-Time Web Applications
  • Network Applications
  • Distributed Systems
  • General Purpose Applications

How many types of API functions are there in Node.js?

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

  • Asynchronous, non-blocking functions
  • Synchronous, blocking functions

What is the difference between Asynchronous and Non-blocking?

Asynchronous Non-blocking
Asynchronous means not synchronous. Using these we can make asynchronous HTTP requests that do not wait for the server to respond. These functions continue to respond to the request for which it has already received the server response. Non-blocking functions are used in regards with I/O operations. They immediately respond with whatever data is available and keeps on running as per the requests. In case, any answer couldn’t be retrieved then the API returns immediately with an error.

In case you are facing any challenges with these Node.js Interview Questions, please mention your problems in the section comment section below.

What is package.json?

The  package.json file in Node.js is the heart of the entire application. It is basically the manifest file that contains the metadata of the project where we define the properties of a package.

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 an Event loop in Node.js and how does it work?

An event loop in Node.js handles all the asynchronous callbacks in an application. It is one of the most important aspects of Node.js and the reason behind Node.js have non-blocking I/O. Since Node.js is an event-driven language, you can easily attach a listener to an event and then when the event occurs the callback will be executed by the specific listener. Whenever functions like setTimeout, http.get, and fs.readFile are called, Node.js executed the event loop and then proceeds with the further code without waiting for the output. Once the entire operation is finished, Node.js receives the output and then executes the callback function. This is why all the callback functions are placed in a queue in a loop. Once the response is received, they are executed one by one.

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.

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

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

Node.js Interview Questions – Moderate Level

What do you understand by a test pyramid?

A test pyramid basically is a diagram that describes the ratio of how many unit tests, integration tests, and end-to-end test are required to be written for the successful development of the project.

a20 1

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: tecklearn});

myPost.save(function(err,myInstance){

if(err){

//handle error and return

}

//go ahead with `myInstance`

});

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 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.

What’s the difference between ‘front-end’ and ‘back-end’ development?

Front-end Development Back-end Development
1. Uses mark up and web languages like HTML, CSS, JavaScript 1. Uses programming and scripting languages like Python, Ruby, Perl, etc.
2. Based on asynchronous requests and AJAX 2. Based on Server Architecture
3. Better Accessibility 3. Enhanced Security
4. Used for SEO 4. Used for Backup

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.

List down the major security implementations within Node.js?

Major security implementations in Node.js are:

  1. Authentications
  2. Error Handling

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(){

....

});

});

});

});

In case you are facing any challenges with these Node.js Interview Questions, please mention your problems in the section comment section below.

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

Explain the concept of middleware in Node.js?

In general, middleware is a function receives the Request and Response objects. In other words, in an application’s request-response cycle these functions have access to various request &  response objects along with the next function of the cycle. The next function of middleware is represented with the help of a variable, usually named next. Most commonly performed tasks by the middleware functions 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

Explain the concept of URL module.

The URL module of Node.js provides various utilities for URL resolution and parsing. It is a built-in module that helps in splitting up the web address into a readable format:
var url = require(‘url’);

For example:

var url = require('url');

var adrs = '<a href="http://localhost:8082/default.htm?year=2019&month=april">
http://localhost:8082/default.htm?year=2019&month=april</a>';

var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8082'

console.log(q.pathname); //returns '/default.htm'

console.log(q.search); //returns '?year=2019 and month=april'

var qdata = q.query; //returns an object: { year: 2019, month: 'april' }

console.log(qdata.month); //returns 'april'

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.

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.

Explain the working of the control flow function.

In Node.js, the control flow function is basically the code that is executed between the asynchronous function calls. Below are the steps that must be followed for executing it:

  1. Firstly, the order of execution must be controlled.
  2. Then, the required data need to be collected.
  3. Next, the concurrency must be limited.
  4. Once done, the next step of the program has to be invoked.

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

Differentiate between spawn() and fork() methods in Node.js?

In Node.js, the spawn() is used to launch a new process with the provided set of commands. This method doesn’t create a new V8 instance and just one copy of the node module is active on the processor. When your child process returns a large amount of data to the Node you can invoke this method.

Syntax:
child_process.spawn(command[, args][, options])
Whereas, the fork() in Node.js is a special instance of spawn() that executes a new instance of the V8 engine. This method simply means that multiple workers are running on a single Node code base for various task.

Syntax:
child_process.fork(modulePath[, args][, options])
In case you are facing any challenges with these Node.js Interview Questions, please mention your problems in the section comment section below.

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.

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.

How assert works in Node.js?

In Node.js, assert is used to write tests. It only provides feedback only when any of the running test cases fails. This module gives you a set of assertion tests which are then used for testing invariants. It is basically used internally by Node.js but using require(‘assert’) code, it can be used in other applications as well.

var assert = require('assert');

function mul(a, b) {

return a * b;

}

var result = mul(1,2);

assert( result === 2, 'one multiplied by two is two');

Define the concept of the test pyramid. Explain the process to implement them in terms of HTTP APIs.

The test pyramid is basically a concept that is developed by Mike Cohn. According to this, you should have a higher number of low-level unit tests as compared to high-level end-to-end tests that running through a GUI.

In terms of HTTP APIs it may be defined as:

  • A higher number of low-level unit tests for each model
  • Lesser integration tests to test model interactions
  • Lesser acceptance tests for testing actual HTTP endpoints

Explain the purpose of ExpressJS package?

Express.js is a framework built on top of Node.js that facilitates the management of the flow of data between server and routes in the server-side applications.  It is a lightweight and flexible framework that provides a wide range of features required for the web as well as mobile application development. Express.js is developed on the middleware module of Node.js called connect. The connect module further makes use of http module to communicate with Node.js. Thus, if you are working with any of the connect based middleware modules, then you can easily integrate with Express.js.

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.

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.

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 stream in Node.js along with its various types.

Streams in Node.js are the collection of data similar to arrays and strings. They are objects using which you can read data from a source or write data to a destination in a continuous manner. It might not be available at once and need not to have fit in the memory. These streams are especially useful for reading and processing a large set of data. In Node.js, there are four fundamental types of streams:

  1. Readable: Used for reading large chunks of data from the source.
  2. Writeable: Use for writing large chunks of data to the destination.
  3. Duplex: Used for both the functions; read and write.
  4. Transform: It is a duplex stream that is used for modifying the data.

Node.js Interview Questions – Advanced Level

What is the use of NODE_ENV?

If the project is in the production stage, Node.js promotes the convention of making use of NODE_ENV variable to flag it. This helps in taking better judgment during the development of the projects. Also, when you set your NODE_ENV to production, your application tends to perform 3 times faster.

Differentiate between readFile vs createReadStream in Node.js?

Node.js provides two ways to read and execute files which are using readFile and CreateStream. readFile() is a fully buffered process which returns the response only when the complete file is pushed into the buffer and is read. It is a memory intensive process and in case of large files, the processing can be very slow. Whereas createReadStream is a partially buffered which treats the entire process as an event series. The entire file is split into chunks which are then processed and sent back as a response one by one. Once done, they are finally removed from the buffer. Unlike readFile, createReadStream is really effective for the processing of the large files.

List down the various timing features of Node.js.

Node.js provides a Timers module which contains various functions for executing the code after a specified period of time. Below I have listed down the various functions provided by this module:

  • setTimeout/clearTimeout– Used to schedule code execution after a designated amount of milliseconds
  • setInterval/clearInterval– Used to execute a block of code multiple times
  • setImmediate/clearImmediate– Used to execute code at the end of the current event loop cycle
  • process.nextTick– Used to schedule a callback function that needs to be invoked in the next iteration of the Event Loop

Explain the concept of Punycode in Node.js?

In Node.js, Punycode is an encoding syntax that is used for converting Unicode (UTF-8) string of characters into a basic ASCII string of characters. It is important as the hostnames can only understand the ASCII characters. Thus, Node.js version 0.6.2 onwards, it was bundled up with the default Node package. If you want to use it with any previous versions, you can easily do that by using the following code:

Syntax:  punycode = require(‘punycode’);

Differentiate between Node.js vs Ajax?

The most basic difference between Node.js and Ajax that, Node.js is a server-side JavaScript whereas Ajax is a client-side technology. In simpler terms, Ajax is mostly used for updating or modifying the webpage contents without having to refresh it. On the other hand, Node.js is required to develop the server software that are typically executed by the servers instead of the web browsers.

Does Node.js provide any Debugger?

Node.js do provide a simple TCP based protocol and debugging client that comes built-in. In order to debug your JavaScript file, you can use the below debug argument followed by .js file name that you want to debug.

Syntax:
node debug [script.js | -e “script” | <host> : <port> ]
In case you are facing any challenges with these Node.js Interview Questions, please mention your problems in the section comment section below.

Describe the exit codes of Node.js.

In Node.js, exit codes are a set of specific codes which are used for finishing a specific process. These processes can include the global object as well. Below are some of the exit codes used in Node.js:

  • Uncaught fatal exception
  • Unused
  • Fatal Error
  • Internal Exception handler Run-time failure
  • Internal JavaScript Evaluation Failure

What do you understand by an Event Emitter in Node.js?

EventEmitter is a Node.js class that includes all the objects that are capable of emitting events. These objects contain an eventEmitter.on() function through which more than one function can be attached to the named events that are emitted by the object. Whenever an EventEmitter object throws an event, all the attached functions to that specific event are invoked synchronously. Below code shows how to us the EventEmitter in your application:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter { }

const myEmitter = new MyEmitter();

myEmitter.on('event', () => {

console.log('an event occurred!');

});

myEmitter.emit('event');

Is cryptography supported in Node.js?

Yes, Node.js does support cryptography through a module called Crypto. This module provides various cryptographic functionalities like cipher, decipher, sign and verify functions, a set of wrappers for open SSL’s hash HMAC etc. For example:

Syntax:

const crypto = require'crypto');

const secret = 'akerude';

const hash = crypto.createHmac('swaEdu', secret).update('Welcome to Tecklearn).digest('hex');

console.log(hash);

Explain the reason as to why Express ‘app’ and ‘server’ must be kept separate.

Express ‘app’ and ‘server’ must be kept separate as by doing this, you will be separating the API declaration from the network related configuration which benefits in the below listed ways:

  • It allows testing the API in-process without having to perform the network calls
  • Faster testing execution
  • Getting wider coverage metrics of the code
  • Allows deploying the same API under flexible and different network conditions
  • Better separation of concerns and cleaner code

API declaration should reside in app.js:

var app = express();

app.use(bodyParser.json());

app.use("/api/events", events.API);

app.use("/api/forms", forms);

Server network declaration should reside in /bin/www:

var app = require('../app');

var http = require('http');

//Get port from environment and store in Express

var port = normalizePort(process.env.PORT || '8000');

app.set('port', port);

//Create HTTP server.

var server = http.createServer(app);

Explain the basics of Node.js.

In its elemental sense, Node.js is a JS runtime built using Chrome’s V8 JavaScript engine as a platform. Node.js has gained popularity as it is lightweight and efficient, majorly due to its event-driven and non-blocking I/O model. Built with performance as its primary focus, Node.js is responsible for processing the JavaScript code into the native machine code, which can then be used by your computer to execute the processes. Even though it is based on the V8 engine, which is used in Google Chrome and other chromium-based browsers (Vivaldi, Brave and Opera), it does not run in the browser itself. During development, various features such as file system API, HTTP library and OS utility methods were added to the engine, so that Node.js can be executed as a program on a computer.

How are ‘Child Threads’ handled in Node.js?

In its core sense, Node.js is a single thread process. Also, it does not expose any child threads and the modes of thread management to the developer. However, child threads may be generated in Node.js in a variety of processes, one of them being asynchronous I/O. Although the child threads spawned through these processes run in the backdrop, they don’t block the main code or execute any application code. But if you require threading support in an application powered by Node.js, multiple tools are available for utilization.

State some differences between Angular JS and Node.js.

Below are some differences between Angular JS and Node.js

Angular JS Node.js
Angular JS is written in TypeScript Node.js is written in a variety of languages, such as C, C++, and JavaScript
It is ideal while creating highly interactive web pages It is suited for small-scale projects and applications
It is an open-source framework for web application development It is a run-time environment based on multiple platforms
Used to create single-page applications for client-side Use to create server-side networking applications
Helps in splitting an application into model-view-controller (MVC) components Helps in generating queries for databases
Appropriate for the development of real-time applications It is appropriate in situations when something faster and highly scalable is required
Angular itself is a web application framework Node.js has many frameworks, including Express.js, Partial.js and more

State the primary uses of Node.js.

  • Complex single-page applications:  Node.js is ideal for creating single-page applications that are complex in nature, such as online drawing tools, mail solutions, and social networking. These types of applications are limited to one-page and the UX is similar to that of a desktop application. Node.js can be used here due to its asynchronous data flow happening at the backend.
  • Real-Time Applications (RTA):  We use a hefty number of Real-Time applications in our day-to-day life. For example, Google Docs, Slack, Skype, WhatsApp and many more. Node.js’ event API, WebSockets, and asynchronous data flow can ensure a faultless server operation, which will update the data instantly.
  • Chat Rooms: This may be clubbed under RTA, but since instant messaging and chatting has emerged as one of the top real-time application models, it needs a special focus. If your product is in this realm, you are looking at requirements such as lightweight, high traffic capacity and substantial data flow. All these requirements can be fulfilled using Node.js and someJavaScript framework at the backend. The aforementioned web sockets come in handy in receiving and sending messages in a chat room environment.
  • Browser-Based Games: The above-mentioned chat rooms can also be integrated into browser-based games, where Node.js is a perfect choice. Combining the Node.js technology with HTML5 and even JS tools will help you create real-time browser-based games.
  • Data Streaming Applications: Another type of application where Node.js is perfect is data streaming applications. The key selling point of these applications is that they can process data in the unloading phase. Through this, while some parts can be downloaded upfront to keep the connection and can download the other parts if and when necessary. In this context, Node.js streaming applications deal with both audio and video data.
  • Representational State Transfer (REST) Application Programming Interfaces (APIs):  APIs based on REST hold a key position in the construction of modern commercial software architecture due to the wide usage of the HyperText Transfer Protocol (HTTP). The Express.js framework of the Node.js ecosystem can help in building fast and light REST APIs.
  • Server-Side Web Applications:  While Node.js and its frameworks can help in creating server-side web applications, it should be noted that CPU-heavy operations should not be expected.
  • Command Line Tools:  Node.js’ expansive ecosystem is an advantage when it comes to building a command line tool, and there are a variety of tutorials available online which can help you build your own CLT.

What is Event-Driven programming?

Event-Driven programming approach profoundly uses events to trigger various functions. In this scenario, an event can be anything, such as the pressing of a key or clicking of a mouse button. Whenever an event occurs, a call-back function already registered with the element is executed, following the ‘publish-subscribe’ pattern. Due to this programming approach, Node.js is faster than other comparable technologies.

In the context of Node.js, what is REPL?

In the context of Node.js, REPL is Read, Eval, Print and Loop. REPL is a computer environment (similar to a Windows console or Linux shell) where any command that is entered is met with a system responded output. The REPL environment is bundled with Node.js by default, and it performs the following tasks:

  • Read: Reads the inputs from the user and converts it into JavaScript data-structure, finally storing it in memory
  • Eval: It receives the data structure and evaluates it
  • Print: It prints the final output
  • Loop: It loops the provided command till CTRL + C is pressed two times

What is a test pyramid in Node.js?

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.

What is libuv?

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

Is Node.js the best platform for CPU-heavy applications?

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.

What is the purpose of the Express JS Package?

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.

What are the main differences between Node.js vs Javascript?

Node.js JavaScript
Cross-platform open-source JS runtime engine. A high-level scripting language based on the concept of OOPS.
Code can be run outside the browser. Code can run only in the browser.
Used on server-side. Used on client-side.
No capabilities to add HTML tags. HTML tags can be added.
Can be run only on Google Chrome’s V8 engine. Can be run on any browser.
Written in C++ and JavaScript. An upgraded version of ECMA script written in C++.

What are the major benefits of Node.js?

Some major benefits of Node.js are:

  • easy to learn and huge community support.
  • easy scalability and high performance.
  • highly extensible with extended support.
  • Full-stack JavaScript.
  • Caching mechanism allows web pages to load faster.
  • Non-blocking I/O systems.

Explain the difference between Asynchronous and Non-blocking?

Asynchronous or non-synchronous means that for a message sent, we will not receive a response immediately; thus, there is no dependency or order of execution. The server stores information and an acknowledgement is received when the action is performed. This improves performance and efficiency.

Non-blocking operation, as the name suggests, does not stop or block any operations. The difference is that non-blocking operation receives a response immediately with whatever data is available. If data is not available, it returns an error. It is mostly used with I/O.

Explain package.json?

The npm packages contain a file package.json in the project root folder, which contains the metadata relevant to the project. It gives information to the npm through which npm identifies a project and its dependencies. Apart from this, it contains other metadata like project description, version, license information and configuration data.

Describe error-first callback in Node.js?

The error-first callback, also called as errorback gives the error and data. It takes a few arguments, the first one being the error object and others being the data. The error-first callback pattern has many advantages: since it is consistent, leads to more adoption, if there is no reference to the data, there is no need to process it. If there is no error, the callback is called with null as the first argument.

What are the main differences between spawn() and fork() methods in Node.js?

Spawn Fork
Designed to run system commands. A special instance of spawn() that runs a new instance of V8.
Does not execute any other code within the node process. Can create multiple workers that run on the same Node codebase.
child_process.spawn(command[, args][, options]) creates a new process with the given command. Special case of spawn() to create child processes using. child_process.fork(modulePath[, args][, options])
Creates a streaming interface (data buffering in binary format) between parent and child process. Creates a communication (messaging) channel between parent and child process.
More useful for continuous operations like data streaming (read/write), example, streaming images/files from the spawn process to the parent process. More useful for messaging, example, JSON or XML data messaging.

What is the purpose of ExpressJS package in Node.js?

ExpressJS package or framework is built on top of Node.js to fast-track the development of single-page, multi-page and hybrid server-based applications. Express is said to be the backend part of the MEAN stack.

Highlight the differences between process.nextTick() and setImmediate().

let execseq = function() {
setImmediate(() => console.log(“immediate”));
process.nextTick(() => console.log(“nextTick”));
console.log(“event loop”);
}

This will execute the “event loop”, then “nextTick” and then “immediate”.

Explain the difference between Node.js vs Ajax?

Ajax is a client-side technology and is used for updating page content without refreshing the same. Node.js is a server-side JavaScript that is used to develop server software. Further, Node.js is a full-fledged development environment, whereas Ajax is used just to obtain data or run scripts.

Explain the Difference between setImmediate() vs setTimeout().

While the word immediate is slightly misleading, the callback happens only after the I/O events callbacks, when we call setImmediate(). setTimeout() is used to set a delay (in milliseconds) for execution of a one-time callback. If we execute,

setImmediate(function() {
console.log(‘setImmediate’)
})
setTimeout(function() {
console.log(‘setTimeout’)
}, 0)

We will get the output as ‘setTimeOut’ and then ‘setImmediate’.

List Out and explain the popular modules of Node.js?

The core modules of Node.js are:

http includes classes, methods and events for creating Node.js http server.
URL contains methods for URL resolution and parsing.
querystring deals with query string.
path contains methods for working with file paths.
fs consists of classes, methods, and events for handling file I/O.
util util module includes utility functions useful for developers.

Add an example of Streams in Node.js?

Example of reading from stream:

var readStream = fs.createReadStream(‘data.txt’);
readStream.on(‘data’, function(chunk) {
data += chunk;
});

Example of writing into stream:

var writeStream = fs.createWriteStream(‘dataout.txt’);
writeStream.write(data,’UTF8′);
writeStream.end();

What is crypto in Node.js? How is it used?

The crypto module in Node.js is used for cryptography, i.e. includes a set of wrappers for open SSL’s hash, HMAC, sign, decipher, cipher and verify functions.

Here is an example of using cipher for encryption:

const crypto = require('crypto');
const cipher = crypto.createCipher('usrnm', 'pwdd');
var encryptd = cipher.update('Welcome to hackr', 'utf8', 'hex');
encryptd += cipher.final('hex');
console.log(encryptd);

Let’s use decipher to decrypt the above to see if we get the same text back:

const crypto = require('crypto');
const decipher = crypto.createDecipher('usrnm', 'pwdd');
var encryptd = '<enter the previous output-encrypted code here>';
var decryptd = decipher.update(encryptd, 'hex', 'utf8');
decryptd += decipher.final('utf8');
console.log(decryptd);

Explain the use of the DNS module in Node.js?

The DNS module is used for resolving a name. It is provided by the operating system and is used for the actual DNS lookup too. With this module, it is not required to memorize the IP addresses as the DNS servers convert domain/subdomain into IP addresses.

Explain the security mechanism of Node.js?

Some mechanisms are:

  • Authorization codes:  We can use authorization codes to secure Node.js. That way, any third party that wants to access Node.js goes through the GET request of the resource provider’s network.
  • Certified Modules:  Certification modules are like filters that scan the libraries of Node.js to identify if any third-party code is present or not. Any hacking can be detected using certifications.
  • Curated Screening register:  This is a quality control system where all the packages (code and software) are checked to ensure their safety. This scan helps to eliminate unverified or unreliable libraries getting into your application.
  • Regular updates:  Downloading the newest version of Node.js will prevent potential hackers and attacks.

Explain various types of API functions in Node.js.

The two types of API functions in Node.js are:

  • Asynchronous/Non-blocking:  These requests do not wait for the server to respond. They continue to process the next request, and once the response is received, they receive the same.
  • Synchronous/Blocking:  These are requests that block any other requests. Once the request is completed, only then the next one is taken up.

What are LTS versions of Node.js?

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.

Explain the working of assert in Node.js

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.

What is callback hell?

In Node.js, callback hell is also known as the Pyramid of Doom. Caused by intensively nested, unreadable and unmanageable callbacks, making the code harder to read and debug. It is caused due to improper execution of the asynchronous logic.

What is stub in Node.js?

Stubs are programs or functions used to stimulate component behavior. Stubs provide the answers to the functions during test cases.

What is Event Loop?

All the asynchronous callbacks are handled by an event loop in Node.js. It is the foundation of the non-blocking input/output in Node.js, making it one of the most vital features of the environment. Due to the nature of Node.js being event-driven, a listener can be attached to an event for the callback to be executed by the former when the event occurs. Node.js executes the event loop and then moves on to the rest of the code, without having to wait for the output. Once the whole operation culminates, it receives the output and the callback function is executed. Once it receives the response, the functions are executed one by one.

What is stream in Node.js? What are its types?

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

List and explain the timing features of Node.js.

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

Highlight the differences between process.nextTick() and setImmediate().

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.

Explain readFile and createReadStream in Node.js.

Both readFile and createReadStream are ways to read and execute files provided by the Node.js.

The readFile process is fully buffered which returns response(s) only if the complete file is entered into the buffer and can be read. This process is highly memory intensive and can become slow in case the file size is large.

The createReadStream process is partially buffered, treating the entire process as a series of events. In this process, the whole files are split into chunks that are processed and then sent as a response individually in succession. Unlike readFile, createReadStream is effective when it comes to reading and processing large files.

Does Node.js provide a Debugger?

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” | :]

Describe the exit codes in Node.js.

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

Why is NODE_ENV used?

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.

What is Event Emitter in Node.js?

Node.js has an EventEmitter class which holds all the objects which can emit events. These objects hold a function called eventEmitter.on() using which multiple functions can be attached to the event emitted by the object. Whenever an object from the EventEmitter class throws an event, all the attached functions to the vent are called upon synchronously.

What is Punycode?

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’);

Explain the concept of JIT and highlight its relation with Node.js.

A JIT or Just-in-time compiler sends bytecode (consisting of interpretable instructions) to the processor by converting it into instruction. Once you are finished with the writing part of a program, the source language statements are compiled into bytecode by the compiler, rather than the code that carries the data which is similar to the destination hardware platform processor.

Node.js employs JIT compilation which improves the speed of code execution to a great extent. It takes the source code and converts it into machine code in runtime. Through this, functions that are called regularly are compiled to machine code, increasing the overall speed of code execution.

Why is the buffer class used in Node.js?

In Node.js, the buffer class stores the raw data, in a manner similar to that of an array of integers. However, it communicates to a raw memory dump, allocated outside the V8 heap. The Buffer class is a global class and can be accessed in an application without having to import the buffer module. It is majorly used as pure JavaScript code is not attuned with binary data.

What is the difference between fork () and spawn () methods in Node.js?

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.

State the steps to write an Express JS application.

To set up an ExpressJs application, you need to follow the following steps:

  • Create a folder with the project name
  • Create a file named package.json inside the folder
  • Run the ‘npm install’ command on the command prompt to install the libraries present in the package file\
  • Create a file named server.js
  • Create the ‘router’ file inside the package consisting of a folder named as index.js
  • The application is created inside the package containing the index.html file

What is Node.js?

Node.js is a JavaScript runtime or platform which is built on Google Chrome’s JavaScript v8 engine. This runtime allows executing the JavaScript code on any machine outside a browser (this means that it is the server that executes the Javascript and not the browser).

Node.js is single-threaded, that employs a concurrency model based on an event loop. It doesn’t block the execution instead registers a callback which allows the application to continue. It means Node.js can handle concurrent operations without creating multiple threads of execution so can scale pretty well.

It uses JavaScript along with C/C++ for things like interacting with the filesystem, starting up HTTP or TCP servers and so on. Due to it’s extensively fast growing community and NPM, Node.js has become a very popular, open source and cross-platform app. It allows developing very fast and scalable network app that can run on Microsoft Windows, Linux, or OS X.

Following are the areas where it’s perfect to use Node.js.

  • I/O bound Applications
  • Data Streaming Applications
  • Data Intensive Real-time Applications (DIRT)
  • JSON APIs based Applications
  • Single Page Applications

At the same time, it’s not suitable for heavy applications involving more of CPU usage.

What are the key features of Node.js?

Let’s look at some of the key features of Node.js.

  • Asynchronous event driven IO helps concurrent request handling –All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response from the previous requests.
  • Fast in Code execution –Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node.js also become faster.
  • Single Threaded but Highly Scalable –Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.
  • Node.js library uses JavaScript –This is another important aspect of Node.js from the developer’s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.
  • There is an Active and vibrant community for the Node.js framework –The active community always keeps the framework updated with the latest trends in the web development.
  • No Buffering –Node.js applications never buffer any data. They simply output the data in chunks.

Explain how do we decide, when to use Node.js and when not to use it?

When should we use Node.js?

It’s ideal to use Node.js for developing streaming or event-based real-time applications that require less CPU usage such as.

  • Chat applications.
  • Game servers.

Node.js is good for fast and high-performance servers, that face the need to handle thousands of user requests simultaneously.

Good for a collaborative environment.

It is suitable for environments where multiple people work together. For example, they post their documents, modify them by doing check-out and check-in of these documents.

Node.js supports such situations by creating an event loop for every change made to the document. The “Event loop” feature of Node.js enables it to handle multiple events simultaneously without getting blocked.

Advertisement servers.

Here again, we have servers that handle thousands of request for downloading advertisements from a central host. And Node.js is an ideal solution to handle such tasks.

Streaming servers.

Another ideal scenario to use Node.js is for multimedia streaming servers where clients fire request’s towards the server to download different multimedia contents from it.

To summarize, it’s good to use Node.js, when you need high levels of concurrency but less amount of dedicated CPU time.

Last but not the least, since Node.js uses JavaScript internally, so it fits best for building client-side applications that also use JavaScript.

When to not use Node.js?

However, we can use Node.js for a variety of applications. But it is a single threaded framework, so we should not use it for cases where the application requires long processing time. If the server is doing some calculation, it won’t be able to process any other requests. Hence, Node.js is best when processing needs less dedicated CPU time.

What IDEs can you use for Node.js development?

Here is the list of most commonly used IDEs for developing node.js applications.

Cloud9.

It is a free, cloud-based IDE that supports, application development, using popular programming languages like Node.js, PHP, C++, Meteor and more. It provides a powerful online code editor that enables a developer to write, run and debug the app code.

JetBrains WebStorm.

WebStorm is a lightweight yet powerful JavaScript IDE, perfectly equipped for doing client-side and server-side development using Node.js. The IDE provides features like intelligent code completion, navigation, automated and safe refactorings. Additionally, we can use the debugger, VCS, terminal and other tools present in the IDE.

JetBrains InteliJ IDEA.

It is a robust IDE that supports web application development using mainstream technologies like Node.js, Angular.js, JavaScript, HTML5 and more. To enable the IDE that can do Node.js development we have to install a Node.js plugin. It provides features, including syntax highlighting, code assistance, code completion and more. We can even run and debug Node.js apps and see the results right in the IDE. It’s JavaScript debugger offers conditional breakpoints, expression evaluation, and other features.

Komodo IDE.

It is a cross-platform IDE that supports development in main programming languages, like Node.js, Ruby, PHP, JavaScript and more. It offers a variety of features, including syntax highlighting, keyboard shortcuts, collapsible Pane, workspace, auto indenting, code folding and code preview using built-in browser.

Eclipse.

It is a popular cloud-based IDE for web development using Java, PHP, C++ and more. You can easily avail the features of Eclipse IDE using the Node.js plug-in, which is <nodeclipse>.

Atom.

It is an open source application built with the integration of HTML, JavaScript, CSS, and Node.js. It works on top of Electron framework to develop cross-platform apps using web technologies. Atom comes pre-installed with four UI and eight syntax themes in both dark and light colors. We can also install themes created by the Atom community or create our own if required.

Explain how does Node.js work?

A Node.js application creates a single thread on its invocation. Whenever Node.js receives a request, it first completes its processing before moving on to the next request.

Node.js works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel. An Event Loop is a functionality which handles and processes all your external events and just converts them to a callback function. It invokes all the event handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request doesn’t have to wait if the processing is not complete.

While processing a request, Node.js attaches a callback function to it and moves it to the back-end. Now, whenever its response is ready, an event is called which triggers the associated callback function to send this response.

Let’s take an example of a grocery delivery.

Usually, the delivery boy goes to each and every house to deliver the packet. Node.js works in the same way and processes one request at a time. The problem arises when any one house is not open. The delivery boy can’t stop at one house and wait till it gets opened up. What he will do next, is to call the owner and ask him to call when the house is open. Meanwhile, he is going to other places for delivery. Node.js works in the same way. It doesn’t wait for the processing of the request to complete (house is open). Instead, it attaches a callback function (call from the owner of the house) to it. Whenever the processing of a request completes (the house is open), an event gets called, which triggers the associated callback function to send the response.

To summarize, Node.js does not process the requests in parallel. Instead, all the back-end processes like, I/O operations, heavy computation tasks, that take a lot of time to execute, run in parallel with other requests.

Explain REPL in Node.js?

The REPL stands for “Read Eval Print Loop”. It is a simple program that accepts the commands, evaluates them, and finally prints the results. REPL provides an environment similar to that of Unix/Linux shell or a window console, in which we can enter the command and the system, in turn, responds with the output. REPL performs the following tasks.

READ

It Reads the input from the user, parses it into JavaScript data structure and then stores it in the memory.

EVAL

It Executes the data structure.

PRINT

It Prints the result obtained after evaluating the command.

LOOP

It Loops the above command until the user presses Ctrl+C two times.

 

Is Node.js entirely based on a single-thread?

Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.

Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.

To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.

How to get Post Data in Node.js?

Following is the code snippet to fetch Post Data using Node.js.

app.use(express.bodyParser());

app.post('/', function(request, response){

console.log(request.body.user);

});

How to make Post request in Node.js?

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)

}

}

);


What is Callback in Node.js?

We may call “callback” as an asynchronous equivalent for a function. Node.js makes heavy use of callbacks and triggers it at the completion of a given task. All the APIs of Node.js are written in such a way that they support callbacks.

For example, suppose we have a function to read a file, as soon as it starts reading the file, Node.js return the control immediately to the execution environment so that the next instruction can be executed. Once file read operation is complete, it will call the callback function and pass the contents of the file as its arguments. Hence, there is no blocking or wait, due to File I/O. This functionality makes Node.js as highly scalable, using it processes a high number of requests without waiting for any function to return the expected result.

What is Callback Hell?

Initially, you may praise Callback after learning about it. Callback hell is heavily nested callbacks which make the code unreadable and difficult to maintain.

Let’s see the following code example.

downloadPhoto('http://coolcats.com/cat.gif', displayPhoto)

function displayPhoto (error, photo) {

if (error) console.error('Download error!', error)

else console.log('Download finished', photo)

}

console.log('Download started')

In this scenario, Node.js first declares the “displayPhoto” function. After that, it calls the “downloadPhoto” function and pass the “displayPhoto” function as its callback. Finally, the code prints ‘Download started’ on the console. The “displayPhoto” will be executed only after “downloadPhoto” completes the execution of all its tasks.

How to avoid callback hell in Node.js?

Node.js internally uses a single-threaded event loop to process queued events. But this approach may lead to blocking the entire process if there is a task running longer than expected.

Node.js addresses this problem by incorporating callbacks also known as higher-order functions. So whenever a long-running process finishes its execution, it triggers the callback associated. With this approach, it can allow the code execution to continue past the long-running task.

However, the above solution looks extremely promising. But sometimes, it could lead to complex and unreadable code. More the no. of callbacks, longer the chain of returning callbacks would be. Just see the below example.

With such an unprecedented complexity, it’s hard to debug the code and can cause you a whole lot of time. There are four solutions which can address the callback hell problem.

  1. Make your program modular.

It proposes to split the logic into smaller modules. And then join them together from the main module to achieve the desired result.

  1. Use async mechanism.

It is a widely used Node.js module which provides a sequential flow of execution.

The async module has <async.waterfall> API which passes data from one operation to other using the next callback.

Another async API <async.map> allows iterating over a list of items in parallel and calls back with another list of results.

With the async approach, the caller’s callback gets called only once. The caller here is the main method using the async module.

  1. Use promises mechanism.

Promises give an alternate way to write async code. They either return the result of execution or the error/exception. Implementing promises requires the use of <.then()> function which waits for the promise object to return. It takes two optional arguments, both functions. Depending on the state of the promise only one of them will get called. The first function call proceeds if the promise gets fulfilled. However, if the promise gets rejected, then the second function will get called.

  1. Use generators.

Generators are lightweight routines, they make a function wait and resume via the yield keyword. Generator functions uses a special syntax <function* ()>. They can also suspend and resume asynchronous operations using constructs such as promises or <thunks> and turn a synchronous code into asynchronous.

Can you create HTTP Server in Nodejs, explain the code used for it?

Yes, we can create HTTP Server in Node.js. We can use the <http-server> command to do so.

Following is the sample code.

var http = require('http');

var requestListener = function (request, response) {

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Welcome Viewers\n');

}

var server = http.createServer(requestListener);

server.listen(8080); // The port where you want to start with.

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

The setImmediate() function is meant to execute a single script once the current event loop is complete.

The setTimeout() function is used to hold a script and schedule it to be run after a certain time threshold is over.

The order of execution will solely depend on the context in which the functions are called. If called from the main module, the timing will be based on the performance of the process.

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

The module.exports function is used to expose two functions and bring them to a usable context. A module is an entity that is used to store relative code in a single snippet. This can be considered as an operation of moving all of the functions into one single file.

Why do you think you are the right fit for this Node.js role?

Here, the interviewer wants to know your understanding of the job role and the company architecture and your knowledge on the topic. While answering this question, it would add immensely if you knew the job description in detail and the basic usage of the technology in the company. The answer can be further elaborated with how your interests align with the technology, job, and the company.

Do you have any past Node.js work experience?

This question is common among Node.js interviews. Make sure to answer it to the best of your abilities, and do not to bloat but give your honest experiences and explain how you’ve used Node.js before. This is used as a measure to see if you have had any hands-on experience with the language in a working environment before.

Do you have any experience working in the same industry as ours?

With this question, the interviewer is trying to assess if you’ve had any previous work experience or internship experience where you dealt with similar working environments or technologies. This line of questioning can be easily answered based on your previous experiences. Make sure to keep it concise and detailed as required when answering this question.

Do you have any certification to boost your candidature for this Node.js role?

It is always advantageous to have a certification in the technology that you’re applying for. This gives the interviewer the impression that you have worked on the technology and that you are serious about using it for your career growth. More than this, it adds immense value to your resume and your knowledge on the topic at the same time.

What is the difference between Nodejs, AJAX, and jQuery?

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.

What are Globals in Node.js?

There are three keywords in Node.js which constitute as Globals. These are Global, Process, and Buffer.

Global:  The Global keyword represents the global namespace object. It acts as a container for all other <global> objects. If we type <console.log(global)>, it’ll print out all of them.

An important point to note about the global objects is that not all of them are in the global scope, some of them fall in the module scope. So, it’s wise to declare them without using the var keyword or add them to Global object.

Variables declared using the var keyword become local to the module whereas those declared without it get subscribed to the global object.

Process:   It is also one of the global objects but includes additional functionality to turn a synchronous function into an async callback. There is no boundation to access it from anywhere in the code. It is the instance of the EventEmitter class. And each node application object is an instance of the Process object.

It primarily gives back the information about the application or the environment.

  • <process.execPath>– to get the execution path of the Node app.
  • <process.Version> –to get the Node version currently running.
  • <process.platform> –to get the server platform.

Some of the other useful Process methods are as follows.

  • <process.memoryUsage> –To know the memory used by Node application.
  • <process.NextTick> –To attach a callback function that will get called during the next loop. It can cause a delay in executing a function.

Buffer:  The Buffer is a class in Node.js to handle binary data. It is similar to a list of integers but stores as a raw memory outside the V8 heap.

We can convert JavaScript string objects into Buffers. But it requires mentioning the encoding type explicitly.

  • <ascii> –Specifies 7-bit ASCII data.
  • <utf8> –Represents multibyte encoded Unicode char set.
  • <utf16le> –Indicates 2 or 4 bytes, little endian encoded Unicode chars.
  • <base64> –Used for Base64 string encoding.
  • <hex> –Encodes each byte as two hexadecimal chars.

Here is the syntax to use the Buffer class.

> var buffer = new Buffer(string, [encoding]);

The above command will allocate a new buffer holding the string with <utf8> as the default encoding. However, if you like to write a <string> to an existing buffer object, then use the following line of code.

> buffer.write(string)

This class also offers other methods like <readInt8> and <writeUInt8> that allows read/write from various types of data to the buffer.

How to load HTML in Node.js?

To load HTML in Node.js we have to change the “Content-type” in the HTML code from text/plain to text/html.
Let’s see an example where we have created a static file in web server.

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 will modify this code to load an HTML page instead of plain text.

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();

});

What is EventEmitter in Node.js?

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.

How many types of Streams are present in Node.js?

Stream in Node.js are objects that allow reading data from a source or writing data to a specific destination in a continuous fashion. In Node.js, there are four types of streams.

  • <Readable> –This is the Stream to be used for reading operation.
  • <Writable> –It facilitates the write operation.
  • <Duplex> –This Stream can be used for both the read and write operations.
  • <Transform> –It is a form of a duplex Stream, which performs the computations based on the available input.

All the Streams, discussed above are an instance of an “EventEmitter” class. The event thrown by the Stream varies with time. Some of the commonly used events are as follows.

  • <data> –This event gets fired when there is data available for reading.
  • <end> –The Stream fires this event when there is no more data to read.
  • <error> –This event gets fired when there is any error in reading or writing data.
  • <finish> –It fires this event after it has flushed all the data to the underlying system.

List and Explain the important REPL commands?

Following is the list of some of the most commonly used REPL commands.

  • <.help> –It displays help for all the commands.
  • <tab Keys> –It displays the list of all the available commands.
  • <Up/Down Keys> –Its use is to determine what command was executed in REPL previously.
  • <.save filename> –Save the current REPL session to a file.
  • <.load filename> –To Load the specified file in the current REPL session.
  • <ctrl + c> –used to Terminate the current command.
  • <ctrl + c (twice)> –To Exit from the REPL.
  • <ctrl + d> –This command perfoms Exit from the REPL.
  • <.break> –It leads Exitting from multiline expression.
  • <.clear> –Exit from multiline expression.

What is NPM in Node.js?

NPM stands for Node Package Manager. It provides following two main functionalities.

  • It works as an Online repository for node.js packages/modules which are present at <nodejs.org>.
  • It works as Command line utility to install packages, do version management and dependency management of Node.js packages.

NPM comes bundled along with Node.js installable. We can verify its version using the following command-

$ npm –version

NPM helps to install any Node.js module using the following command.

$ npm install <Module Name>

For example, following is the command to install a famous Node.js web framework module called express-

$ npm install express

What is the global installation of dependencies?

Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js, but cannot be imported using require() in the Node application directly.

To install a Node project globally use -g flag as.

C:\Nodejs_WorkSpace>npm install express -g

What is the local installation of dependencies?

By default, NPM installs any dependency in the local mode. It means that the package gets installed in “node_modules” directory which is present in the same folder, where Node application is placed. Locally deployed packages are accessible via require(). Following is the syntax to install a Node project locally.

C:\Nodejs_WorkSpace>npm install express

What is package.json? Who uses it?

What is <package.json>?

  • It is a plain JSON (JavaScript Object Notation) text file which contains all metadata information about Node.js Project or application.
  • This file should be present in the root directory of every Node.js Package or Module to describe its metadata in JSON format.
  • The file is named as “package” because Node.js platform treats every feature as a separate component. Node.js calls these as Package or Module.

Who use it?

  • NPM (Node Package Manager) uses <package.json> file. It includes details of the Node.js application or package. This file contains a no. of different directives or elements. These directives guide NPM, about how to handle a module or package.

Does Node.js support multi-core platforms? And is it capable of utilizing all the cores?

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.

Which is the first argument usually passed to a Node.js callback handler?

Node.js core modules follow a standard signature for its callback handlers and usually the first argument is an optional error object. And if there is no error, then the argument defaults to null or undefined.

Here is a sample signature for the Node.js callback handler.

function callback(error, results) {

// Check for errors before handling results.

if ( error ) {

// Handle error and return.

}

// No error, continue with callback handling.

}

What is chaining process in Node.js?

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.

How to create a custom directive in AngularJS?

To create a custom directive, we have to first register it with the application object by calling the <directive> function. While invoking the <register> method of <directive>, we need to give the name of the function implementing the logic for that directive.

For example, in the below code, we have created a copyright directive which returns a copyright text.

app.directive('myCopyRight', function ()

{

return

{

template: '@CopyRight MyDomain.com '

};

});

Note – A custom directive should follow the camel case format as shown above.

What is a child_process module in Node.js?

Node.js supports the creation of child processes to help in parallel processing along with the event-driven model.

The Child processes always have three streams <child.stdin>, child.stdout, and child.stderr. The <stdio> stream of the parent process shares the streams of the child process.

Node.js provides a <child_process> module which supports following three methods to create a child process.

  • exec – <child_process.exec>method runs a command in a shell/console and buffers the output.
  • spawn – <child_process.spawn>launches a new process with a given command.
  • fork – <child_process.fork>is a special case of the spawn() method to create child processes.

What are the different custom directive types in AngularJS?

AngularJS supports a no. of different directives which also depend on the level we want to restrict them.

So in all, there are four different kinds of custom directives.

  • Element Directives (E)
  • Attribute Directives (A)
  • CSS Class Directives (C)
  • Comment Directives (M)

What is a control flow function? What are the steps does it execute?

It is a generic piece of code which runs in between several asynchronous function calls is known as control flow function.

It executes the following steps.

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

What is the difference between Node.js and JavaScript?

Factor Node.js JavaScript
Engine V8 – Google Chrome V8, Spider Monkey, and JS Core
Usage To perform non-blocking activities For general client-side operations
Working Interpreter – Scripting Programming Language

What is Node.js?

Node.js is a very popular scripting language that is primarily used for server-side scripting requirements. It has numerous benefits compared to other server-side programming languages out there, the most noteworthy one being the non-blocking I/O.

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.

Where is Node.js used?

Node.js is used in a variety of domains. But, it is very well regarded in the design of the following concepts:

  • Network application
  • Distributed computing
  • Responsive web apps
  • Server–Client applications

Next up on these Node js interview questions, you have to understand a very vital difference. Read on.

What is the difference between Node.js and Angular?

Node.js Angular
Used in situations where scalability is a requirement Best fit for the development of real-time applications
Ability to generate queries in a database Ability to simplify an application into the MVC architecture
Mainly used to develop small/medium-sized applications Mainly used to develop real-time interactive web applications
Provides many frameworks such as Sails, Partial, and Express Angular is an all-in-one web app framework
Coded using C++ and JavaScript Coded in TypeScript

Why is Node.js single-threaded?

Node.js works on the single-threaded model to ensure that there is support for asynchronous processing. With this, it makes it scalable and efficient for applications to provide high performance and efficiency under high amounts of load.

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

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

  • Synchronous APIs: Used for non-blocking functions
  • Asynchronous APIs: Used for blocking functions

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.

Next among the Node js questions, we have to check out about control flow function.

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.

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:

  • Writing JavaScript on the server
  • Access to the HTTP stack
  • File I/O entities
  • TCP and other protocols
  • Direct database access

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.

What are the asynchronous tasks that should occur in an event loop?

Following are some of the tasks that can be done using an event loop asynchronously:

  • Blocking send requests
  • High computational requirement
  • Real-time I/O operations

What is the order of execution in control flow statements?

The following is the order in which control flow statements are used to process function calls:

  • Handling execution and queue
  • Data collection and storage
  • Concurrency handling and limiting
  • Execution of the next piece of code

What are the input arguments for an asynchronous queue?

There are two main arguments that an asynchronous queue uses. They are:

  • Concurrency value
  • Task function

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 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 up on these Node js interview questions, need to understand how you can import libraries into Node.js.

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 meant by event-driven programming in Node.js?

Event-driven programming is a technique in which the workflow execution of a program is mainly controlled by the occurrence of events from external programs or other sources.

The event-driven architecture consists of two entities, namely:

  • Event handling
  • Event selection

What is the framework that is used majorly in Node.js today?

Node.js has multiple frameworks, namely:

  • Hapi.js
  • Express.js
  • Sails.js
  • Meteor.js
  • Derby.js
  • Adonis.js

Among these, the most used framework is Express.js for its ability to provide good scalability, flexibility, and minimalism.

What are the security implementations that are present in Node.js?

Following are the important implementations for security:

  • Error handling protocols
  • Authentication pipelines

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.

Next up on these Node js interview questions, it is vital that you know about Libuv. Read on.

What is libuv?

Libuv is a widely used library present in Node.js. It is used to complement the asynchronous I/O functionality of Node.js. It was developed in-house and used alongside systems such as Luvit, Julia, and more.

Following are some of the features of libuv:

  • File system event handling
  • Child forking and handling
  • Asynchronous UDP and TCP sockets
  • Asynchronous file handling and operations

Next among the Node js questions, you need to understand a question about the functioning of Google Chrome.

Why does Google use the V8 engine for Node.js?

Google makes use of the V8 engine because it can easily convert JavaScript into a low-level language. This is done to provide high performance during the execution of an application and also to provide users with real-time abilities to work with the application.

What is the difference between spawn and fork methods in Node.js?

The spawn() function is used to create a new process and launch it using the command line. What it does is that it creates a node module on the processor. Node.js invokes this method when the child processes return data.

The following is the syntax for the spawn() method:

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

Coming to the fork() method, it can be considered as an instance of the already existing spawn() method. Spawning ensures that there are more than one active worker node to handle tasks at any given point of time.

The following is the syntax for the fork() method:

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

What is the use of middleware in Node.js?

A middleware is a simple function that has the ability to handle incoming requests and outbound response objects. Middleware is used primarily for the following tasks:

  • Execution of code (of any type)
  • Updation of request and response objects
  • Completion of request–response iterations
  • Calling the next middleware

What are global objects in Node.js?

Global objects are objects with a scope that is accessible across all of the modules of the Node.js application. There will not be any need to include the objects in every module. One of the objects is declared as global. So, this is done to provide any functions, strings, or objects access across the application.

Next among the Node js coding questions you need to take a look at the usage of assets in Node js.

Why is assert used in Node.js?

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');

What are stubs in Node.js?

Stubs are simply functions that are used to assess and analyze individual component behavior. When running test cases, stubs are useful in providing the details of the functions executed.

How is a test pyramid implemented using the HTML API in Node.js?

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

Why is a buffer class used in Node.js?

A buffer class is primarily used as a way to store data in Node.js. This can be considered as a similar implementation of arrays or lists. Here, the class refers to a raw memory location that is not present in the V8 heap structure.

The buffer class is global, thereby extending its usage across all the modules of an application.

Why is ExpressJS used?

ExpressJS is a widely used framework built using Node.js. Express.js uses a management point that controls the flow of data between servers and server-side applications.

Being lightweight and flexible, Express.js provides users with lots of features used to design mobile applications.

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

The connect module in Node.js is used to provide communication between Node.js and the HTTP module. This also provides easy integration with Express.js, using the middleware modules.

What are streams in Node.js?

Streams are a set of data entities in Node.js. These can be considered similar to the working of strings and array objects. Streams are used for continuous read/write operations across a channel. But, if the channel is not available, then all of the data cannot be pushed to the memory at once. Hence, using streams will make it easy to process a large set of data in a continuous manner.

Next up on this compilation of top node js interview questions for experienced, let us check out the advanced category of questions.

Advanced Interview Questions

What are the types of streams available in Node.js?

Node.js supports a variety of streams, namely:

  • Duplex (both read and write)
  • Readable streams
  • Writable streams
  • Transform (duplex for modifying data)

What is the use of REPL in Node.js?

REPL stands for Read-Eval-Print-Loop. It provides users with a virtual environment to test JavaScript code in Node.js.

To launch REPL, a simple command called ‘node’ is used. After this, JavaScript commands can be typed directly into the command line.

What is meant by tracing in Node.js?

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.

Where is package.json used in Node.js?

The ‘package.json’ file is a file that contains the metadata about all items in a project. It can also be used as a project identifier and deployed as a means to handle all of the project dependencies.

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

  • 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.

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

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.

What is a passport in Node.js?

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.

How to get information about a file in Node.js?

The fs.stat function is used to get the required information from a file.

The syntax is as follows:

fs.stat(path, callback)

where,

  • Path is the string that has the path to the name
  • Callback: The callback function where stats is an object of fs.stats

Next up on these Node js interview questions, you need to understand about DNS lookup.

How does the DNS lookup function work in Node.js?

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)

What is the use of EventEmitter in Node.js?

Every single object in Node.js that emits is nothing but an instance of the EventEmitter class. These objects have a function that is used to allow the attachment between the objects and the named events.

Synchronous attachments of the functions are done when the EventEmitter object emits an event.

 

 

So, this brings us to the end of the NodeJS Interview Questions blog.
This Tecklearn  ‘Top NodeJS Interview Questions and Answers’helps you with commonly asked questions if you are looking out for a job in Front End Development.

 

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Top Node JS Interview Questions and Answers"

Leave a Message

Your email address will not be published. Required fields are marked *