Home >> Interviews Q & A >> Node.js Interview Questions Answers

Node.js Interview Questions Answers

Node.js Interview Questions: Node.js Interview Questions and Answers for freshers and Experienced. Basic and Advanced Node.js Questions. Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.
Node.js Interview Questions

Node.js Interview Questions | Basic

Q:- What Is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment for executing JavaScript code on server side.
Most Popular JavaScript Engine:
  1. Google Chrome - V8 // Fastest JavaScript Engine
  2. Mozilla FireFox - SpiderMonkey
  3. Microsoft Edge - Chakra
Q:- How to Install Node.js?

It's very easy to Install Node.js on Windows, Linux, etc

Q:- In which Language Node.js is Written?

Node.js is written in‎ - ‎C‎, ‎C++‎, ‎JavaScript and it's original author(s)‎ is ‎Ryan Dahl

Q:- What are the key features of Node.js?

Node.js has many features which makes node.js more powerful.

  1. Asynchronous and Event Driven –

    All APIs of Node.js library are asynchronous, that is, non-blocking I/O.

    Node.js can handle multiple concurrent request, it's the power of node.js. After it finish executing request it will run a callback to notify about its completion.

  2. It's very fast –

    Node.js uses the Google Chrome's V8 JavaScript Runtime Engine written in C++, which compiles the JavaScript code into machine code, which makes node.js faster.

    JavaScript Engine: It is a program that converts JavaScript's code into lower-level or machine code.

  3. Single Threaded but Highly Scalable –

    Node.js is a single threaded, which in background (Under the hood Node.js uses many threads through libuv) uses multiple threads to execute asynchronous code.

    Node.js applications uses Single Threaded Event Loop Model to handle multiple concurrent requests.

    The Event Loop mechanism helps the server to respond in a non-blocking way, resulting in making the server highly scalable as opposed to traditional servers which create limited threads to handle requests.

  4. Node.js library uses JavaScript –

    Since, majority of developers are already using JavaScript. so, development in Node.js becomes easier for a developer who already knows JavaScript.

  5. NPM (Node Package Manager) –

    NPM stands for Node Package Manager, it allows us to install various Packages for Node.js Application.

  6. No Buffering –

    Node.js applications never buffer any data. They simply output the data in chunks.

  7. Community –

    Node.js has a very good community which always keeps the framework updated with the latest trends in the web development.

Q:- What is NPM? What is the need of NPM in Node.js?

NPM stands for Node Package Manager, it comes with node.js & allows us to install various packages for Node.js Applications.

npm install express --save
npm install lodash --save
Q:- How to check globally installed dependencies using NPM?
npm ls -g
Q:- What is NVM? What is the use of NVM in Node.js?

NVM stands for Node Version Manager, You can use nvm to change your node.js versions very easily this is very helpful if you are working on multiple projects of Node.js having different versions, etc.

Q:- What is Nodemon?
Nodemon is a tool which monitor node.js applications for any changes in your source code and it automatically restart your server.
  • Nodemon is the best tool for development,while developing node.js project.
  • Nodemon is available as NPM Package.
  • You can also install nodemon as a development dependency:
npm install nodemon --save-dev
nodemon [your node app]

//Example 
nodemon app.js //app.js is the main file of your Node.js project.
Q:- What is REPL in Node.js (Read-Eval-Print Loop)?
  1. The REPL stands for "Read Eval Print Loop". It is a simple program that accepts the commands, evaluates them, and finally prints the results.
  2. 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.
  3. To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC.
REPL allows for the easy creation of CLI (Command Line Interface) applications.
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 repeat the above command until the user presses Ctrl+C two times.

Node.js Interview Questions | Intermediate

Q:- What are LTS releases? Why are they important?
  • LTS: stands for Long Term Support. LTS releases receives all the critical bug fixes, security updates and performance improvements.
  • LTS version have community support and maintenance for at least 18 months, therfore it is good to use Active LTS or Maintenance LTS releases in Production.
  • Importance of LTS Version: Once a Current release line becomes LTS, no new features or breaking changes will be added to that release.
Q:- What is difference between LTS and Stable version of Node.js?

LTS:- Long Term Support (LTS) version has at least 18 months support and maintenance, so it's more stable and secure.

Stable:- Current Stable version has 8 months support and maintenance.

Q:- How to get Post data in Node.js?
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.post("/", function (req, res) {
    console.log(req.body.message);
});
Q:- How to make GET/Post request in Node.js?

Following is an simple example of HTTP GET/POST request in Node.js

//GET:

var request = require('request');

// Set the headers
var headers = {
    'Content-Type':'application/x-www-form-urlencoded'
}

// Configure the request
var options = {
    url: 'https://www.fullstacktutorials.com',
    method: 'GET',
    headers: headers,
    qs: {'message': 'Node.js Interview Questions'}
}

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body)
    }
})
//The above code will make a GET  request like - http://localhost:3000/?message=Node.js Interview Questions



//POST:
var request = require('request');

// Set the headers
var headers = {
    'Content-Type':'application/x-www-form-urlencoded'
}

// Configure the request
var options = {
    url: 'https://www.fullstacktutorials.com',
    method: 'POST',
    headers: headers,
    form: {'message': 'Node.js Interview Questions'}
}

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body)
    }
})
//The above code will make a POST request like - http://localhost:3000/ with parameter message=Node.js Interview Questions.
You may also like - MongoDB Interview Questions Answers
Q:- What is the key difference between Ajax and Node.js?

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 a Server-side JavaScript runtime environment.

You may also like - JavaScript ES6 Interview Questions
Q:- What is Callback in Node.js?

A callback is a function, which is called automatically at the completion of a given task. Node makes heavy use of callbacks.

#Examples:
var myCallback = function(err, data) {
  if (err) throw err; // Check for the error and throw if it exists.
  console.log('Your Data is: ' +data); // Process the data.
};

var myFunc = function(callback) {
  callback(null, 'This is Callback Example in Node.js'); // I don't want to throw an error, so I pass null for the error argument
};

//Call your function 
myFunc(myCallback);
Q:- What is "Callback Hell" and how can it be avoided?

Callback hell refers to a coding pattern where there is a lot of nesting of callback functions. The code forms a pyramid-like structure and it becomes difficult to debug. Sometime it is called - pyramid of doom.

Just imagine if you need to make callback after callback:

getDetails(function(a){  
    getMoreDetails(a, function(b){
        getMoreDetails(b, function(c){ 
            getMoreDetails(c, function(d){ 
                getMoreDetails(d, function(e){ 
                    //and so on...
                });
            });
        });
    });
});
Callback Hell can be avoided by using:
  1. Modularizing code
  2. using promises
  3. using async/await
Q:- What is error first callback node.js?
  1. The first argument of the callback is reserved for an error object. If an error occurred, it will be returned by the first err argument.
  2. The second argument of the callback is reserved for any successful response data. If no error occurred, err will be set to null and data will be returned in the second argument.
fs.readFile('myfile.txt', function(err, data) {
// If an error occurred, handle it (throw etc)
if(err) {
	console.log('Error Found:' + err);
	throw err;
}
// Otherwise, log or process the data
console.log(data);
});
Q:- How to catch all uncaughtException for Node.js?

Use process 'uncaughtException' and 'unhandledRejection' events

process
  .on('unhandledRejection', (reason, p) => {
    console.error(reason, 'Unhandled Rejection at Promise', p);
  })
  .on('uncaughtException', err => {
    console.error(err, 'Uncaught Exception thrown');
    process.exit(1);
  });
You may also like - JavaScript Interview Questions
Q:- What is package.json in node.js?
  1. The package.json is a json file which holds all the metadata information about your node.js Application.
  2. NPM (Node Package Manager) uses this package.json to manage all modules/packages dependencies for your node.js application. it will install all the dependencies to ./node_modules directory.
  3. The package.json file is normally located at the root directory of your node.js project.
{
  "name": "myApp",
  "version": "1.0.0",
  "description": "This is my first node.js app.",
  "main": "app.js",
  "homepage": "https://www.fullstacktutorials.com"
  "author": "Full Stack Tutorials",
  "license": "ISC",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js",
  },
  "dependencies": {
    "body-parser": "^1.18.2",
    "debug": "^3.1.0",
    "express": "^4.16.2",
    "mongoose": "^5.0.4",
    "mysql": "^2.15.0",
    "nodemon": "^1.17.2",
    "request": "^2.83.0"
  },
  "devDependencies": {},
  "repository": {}
}

Following are the some important attributes of package.json
  1. name - name of the package
  2. version - version of the package
  3. author - author of the package
  4. dependencies - list of dependencies. npm automatically installs all the dependencies mentioned here in the node_module folder of the package.
Q:- Difference between package.json and package-lock.json?

package.json: The package.json is used for more than dependencies - like defining project properties, description, author & license info etc.

package-lock.json: The package-lock.json is primarily used to lock dependencies to a specific version number.

If package-lock.json exists, it overrules package.json

Q:- How to uninstall a dependency using npm?
 npm uninstall dependency-name
Q:- How to update dependency using npm?
npm update [-g] [...]

npm update
Q:- What's the difference between a tilde (~) and a caret (^) in a npm package.json file?

The version number is in semver syntax - major.minor.patch

Tilde Dependencies:

If your app's package.json contains:

"dependencies": {
  "module_name": "~1.0.2"
}

it means to install version 1.0.2 or the latest patch version such as 1.0.4

Caret Dependencies:

If your app's package.json contains:

"dependencies": {
  "module_name": "^1.0.2"
}

If you see ^1.0.2 it means to install version 1.0.2 or the latest minor or patch version such as 1.1.0

Node.js Interview Questions | Advanced

Q:- What is a blocking code?

If an application has to wait for some I/O operation in order to complete its execution any further than the code responsible for waiting is known as blocking code.

Q:- What is Chaining in Node.js?

Chaining is a mechanism in node.js to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.

You may also like - React.js Interview Questions
Q:- What is Modules in Node.js?

This is mostly frequently asked Node.js Interview Questions.

Modules is a set of functionality or javascript libraries encapsulated into a single unit, which can be reused throughout the Node.js application.

Each Node.js modules has it's own context.

Type of Modules in Node.js?
  1. Core (In-built) Modules
  2. Local (User defined) Modules
  3. 3rd Party Modules
1. Core Modules:

Node.js Core Modules comes with its Installation by default. You can use them as per application requirements

Include and Use Core Modules with Example:

First you need to import core module using require() function.

const http = require('http');

var server = http.createServer(function(req, res){
	console.log("Congrats!, Node.js is running on Port 3000");
});

server.listen(3000); 
2. Local Modules:

Local modules are user defined modules which are mainly used for specific projects and locally available in separate files or folders within project folders.

Include and Use Local Module with Example:

First you need to import core module using require() function.

Create a folder common, inside common folder create a new file named utility.js with following code

//create module and export
function log(message) {  
	console.log(message);
}  
module.exports = log; 

Now, inside app.js or index.js file import that utility module using require() function.

//load/import module and use
const logger = require('./common/utility');   
var output = logger.log("Congrats!, You have successfully created a local module!");  
console.log(output); 
3. 3rd Party Modules:

The 3rd party modules can be downloaded using NPM (Node Package Manager).

Include and Use 3rd Party Module with Example:
//Syntax
npm install -g module_name // Install Globally
npm install --save module_name //Install and save in package.json

//Install express module
npm install --save express  
npm install --save mongoose

//Install multiple module at once
npm install --save express mongoose
Q:- How many ways you can Make HTTP Requests in Node.js?

There are many ways you can make HTTP requests in Node.js, Few of them are given below, which are mostly used:

  1. HTTP – the Standard Library
  2. Request
  3. Axios
Q:- Explain some important concepts in Node.js?
  1. Debugger: Statement inserting debugger, in the code of java script it will help to enable break point.
  2. Console: Console module provides debugging feature that is similar in Java script console by browser.
  3. Streaming: A stream is an abstract interface implemented by various objects in Node.js
  4. Cluster: It allows us to create child process easily that shares server port.
  5. DNS: DNS module contains functions.
  6. Add-ons: It is a dynamically linked shared object.
  7. Domain: It provides a way to handle multiple different IO operations as a single group.
  8. Buffer: It is similar to array of integers but corresponds to fixed-sized.
  9. Global: It is available for all modules.
  10. Net: It provides asynchronous network wrapper.
  11. Callbacks: It is called when given task will be completed.
  12. Error handling: It supports various types of categories error.
  13. Crypto: It provides cryptographic functionality that includes a set of wrappers for Open SSL’s hash.
Q:- Explain how do we decide, when to use Node.js and when not to use it?
Use Node.js:
  • Single Page Applications
  • Real-Time services (Chat Applications, Games Servers etc)
  • REST APIs and Backend Applications
  • Blogs, CMS, Social Applications.
  • Data Streaming Applications
  • Utilities and Tools
  • Advertisement Servers.
In Short, it's good to use Node.js, when you need high levels of concurrency but less amount of dedicated CPU time.
Don't use Node.js:

we should not use node.js for cases where the application requires long processing time. So, Node.js is best suited when processing needs less dedicated CPU time.

In Short, it's not good for CPU intensive tasks.
Q:- Why should you separate Express 'app' and 'server'?

Short Answer - Performace Optimization, Sepeartion between Code & Server related stuff, Easy Testing etc.

Express App is responsible for Code Logics, DB Connections, API Stuff etc. while Server is responsible for network related stuff like port, protocol etc.

So API declaration, Code Logics etc, should reside in app.js and Server network declaration, should reside in /bin/www

Q:- Is Node.js Single-threaded OR Multi-threaded?
Node.js is Single-threaded

it's true that Node.js processes all requests on a single thread. In fact, more than the single thread mechanism, it makes use of events loop and callbacks to handle a large no. of concurrent requests asynchronously.

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

#Example:
To explain it practically, suppose 500 requests are lined up in Node.js Event Queue. As per the 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.

Q:- How does node.js takes advantage of Multi-Core Systems, Since we all know that node.js is Single Threaded?

Generally, if the child process or cluster modules are not involved, then there is no benefit from having multi-core system, because Node.js will only use one core.

A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.

The cluster module allows easy creation of child processes that all share server ports.

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}

Running Node.js will now share port 8000 between the workers:

Source: nodejs official website

$ node app.js
Master 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started

The worker processes are spawned using the child_process.fork() method, so that they can communicate with the parent via IPC and pass server handles back and forth.

If you are using PM2 Process Manager then you can use

pm2 start app.js -i max

//Example
pm2 start app.js -i 8
Q:- What is Reactor Pattern in Node.js?

The reactor design pattern is an event handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers.

  1. Application generates new I/O operation by submitting request to Event Demultiplexer. (aka: event notification interface) The application also specifies handler/callback function which will be invoked when operation completes.
  2. Submitting a new request to the Event Demultiplexer is a non-blocking call and it immediately returns the control back to the application.
  3. When an I/O operation completes, the Event Demultiplexer pushes the new events into the Event Queue(aka: CallStack).
  4. The Event Loop iterates over the items of the Event Queue. for each event, the associated callback function is invoked. callback function will give control to the event loop when its execution completes.
  5. New Asynchronous operations might be requested during the execution of the callback function, causing new operations to be inserted in the Event Demultiplexer.
  6. When all items in Event Queue are processed, the loop will block again on the Event Demultiplexer which will then trigger another cycle when a new event is available.

A Node.js application will exit automatically when there are no more pending operations in the Event Demultiplexer, and no more event to be processed inside the Event Queue.

Q:- What is libuv in Node.js?
  1. libuv is library written in C language to make Node.js compatible with every OS and provide the non-blocking I/O behaviour.
  2. Each operating system has its own interface for the Event Demultiplexer. eg: epoll on Linux, kqueue on Mac OS X & IOCP on Windows.
  3. libuv is a C library, created to make Node.js compatible with every OS & normalize the non-blocking behavior of the different OS types.
  4. libuv is a low-level I/O Engine.
  5. libuv provides a threadpool (threadpool is global and shared across all event loops.) which can be used to run user code and get notified in the loop thread.
  6. Its default size is 4, but it can be changed at startup time by setting the UV_THREADPOOL_SIZE environment variable to any value (the absolute maximum is 1024)..
Q:- Which are best suited IDEs for Node.js?

There are too many IDEs some of them which are most popular are listed below.

You may also like - Top 10 Express.js Interview Questions
Full Stack Tutorials

Author @FullStackTutorials | View all Articles