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
  2. It's very fast
  3. Single Threaded & Highly Scalable
  4. Node.js library uses JavaScript
  5. NPM (Node Package Manager)
  6. No Buffering
  7. Community

Let's see all above node.js feature details

  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 & 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 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)?
REPL allows for the easy creation of CLI (Command Line Interface) applications.
  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. It will change the prompt to > in Windows and MAC.
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.

Q:- How do I exit/end a node.js process?

There are mainly 2 ways

  1. using process.exit()
  2. Press Ctrl + C twice, or type .exit and press Enter

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 resolve cross origin (CORS) issue in node.js?

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources to be requested from another domain/server.

There are mainly three ways you can do this using
  1. res.setHeader()
  2. res.header() OR res.set()
  3. express cors module

If you are using express.js you can use cors module

Q:- Difference between res.setHeader() and res.header() in node.js?

Both two methods do exactly the same thing, set the headers HTTP response.

res.setHeader() res.header()
It is a native method of node.js It is an alias of res.set() method from express framework
It allows you to set only a single header It allows you to set multiple headers
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.

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.

It is also 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 promise
  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 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 OR //for npm >= 5.0.0 npm install express npm install lodash

Note: As of npm 5.0.0 and greater, installed modules are added as a dependency by default, so the --save option is no longer needed.

Q:- How to check globally installed dependencies using NPM?
npm ls -g
Read more details about NPM

Q:- What is NVM? What is the use of NVM in Node.js?

NVM stands for Node Version Manager

  • NVM helps to use and manage multiple versions of node.js.
  • You can use nvm to change your node.js versions very easily.
  • NVM is very helpful if you are working on multiple projects of Node.js having different versions.
Read more details about NVM

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 uses this package.json to manage all modules/packages dependencies for your node.js application.
  3. It will install all the dependencies to ./node_modules directory.
  4. 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", "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" }, "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] [<pkg>...] 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 modules 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 - Deprecated! (Feb 11th 2020)
  3. Axios - Promise based HTTP client for the browser and node.js
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?

Yes, Node.js is Single-threaded

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

There are mainy two ways to achieve this

  1. cluster module
  2. PM2

Cluster is a module of Node.js that contains sets of functions and properties that helps the developers for forking processes through which they can take advantage of the multi-core system.

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:

If you are using PM2 - Process Manager then you can directly use

pm2 start app.js -i max //Example pm2 start app.js -i 5

cluser.fork is implemented on top of child_process.fork. one more thing that cluster.fork brings is, it enables you to listen on a shared port.

Q:- What is Reactor Pattern in Node.js?
The reactor design pattern is an event handling pattern.

It is used 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.

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. 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.
  3. 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:- What is the Event Loop?

Event loop allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.

Q:- What is the difference between setImmediate() and process.nextTick()?
process.nextTick() and setImmediate() are used to schedule callbacks in the event loop.
setImmediate()

Any function passed as the setImmediate() argument is a callback that’s executed in the next iteration of the event loop.

setImmediate(() => { //code block })
process.nextTick()

A function passed to process.nextTick() is going to be executed on the current iteration of the event loop, after the current operation ends.

process.nextTick(() => { //code block })
Q:- What is Event Emitter?

As we all know in browser, javascript provides various events - onclick, onmouseover, etc likewise node.js provides events module to handle such events at server side.

const EventEmitter = require('events'); const eventEmitter = new EventEmitter();

This object expose two methods

  1. emit is used to trigger an event.
  2. on is used to add a callback function which will be executed when the event is triggered.
Example - Emit and listen events
//Listen the Start event eventEmitter.on('start', () => { console.log('started') }); //trigger the start event eventEmitter.emit('start')

addListener() is an alias of on() in Node.js

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