Home >> Interviews Q & A >> Node Js Interview Questions

Node Js Interview Questions

Node Js Interview Questions: Node js interview questions and answers for experienced. Node js is a JavaScript runtime built on Chrome's V8 JavaScript engine.
Q:- What Is Node Js?
Node Js is an open-source, cross-platform JavaScript runtime environment for executing JavaScript code on server side.

Ryan Dahl came up with a brilliant idea, he thought it would be great to execute JavaScript outside the browser means on the Server, so he took Google's JavaScript V8 Engine and embedded with C++ Program and called it Node, So Node is Runtime Environment for executing JavaScript Code.

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.

Most Popular JavaScript Engine:
  1. Google Chrome - V8 // Fastest JavaScript Engine
  2. Mozilla FireFox - SpiderMonkey
  3. Microsoft Edge - Chakra
Q:- Why Node Js?
"Node Js uses asynchronous programming!"

A common task for a web server can be to open a file on the server and return the content to the client.

Here is how PHP or ASP handles a file request:

  • Sends the task to the computer's file system.
  • Waits while the file system opens and reads the file.
  • Returns the content to the client.
  • Ready to handle the next request.

Here is how Node js handles a file request:

  • Sends the task to the computer's file system.
  • Ready to handle the next request.
  • When the file system has opened and read the file, the server returns the content to the client.
  • Node js eliminates the waiting, and simply continues with the next request.
Q:- What are the key features of Node Js?

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

  1. Asynchronous and Event Driven –
    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.
  2. It's very fast –
    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.
  3. 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.
  4. 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.
  5. Community –
    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.
  6. No Buffering –
    Node js applications never buffer any data. They simply output the data in chunks.
  7. NPM (Node Package Manager) –
    NPM stands for Node Package Manager, it comes with node js & allows us to install various Packages for Node js Application.
Q:- Explain how do we decide, when to use node js and when not to use it?
Use Node Js:

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

  • Single Page Applications
  • REST APIs and Backend Applications
  • Real-Time services (Chat, Games etc)
  • Blogs, CMS, Social Applications.
  • Data Streaming Applications
  • Utilities and Tools
  • Anything that is not CPU intensive, means it’s not suitable for heavy applications involving more of CPU usage.
  • Chat applications.
  • Game servers.
  • Advertisement Servers.
To summarize, 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:

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.

Q:- Explain REPL In Node Js (Read-Eval-Print Loop)?

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.

You may also like - MongoDB Interview Questions Answers
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. 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 loop 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.

#Example:
To explain it practically, let’s assume there are 500s 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.

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 is the key difference between Ajax and Node.js?

Ajax is a client-side technology while Node.js is a server-side JavaScript 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. All the APIs of Node are written in such a way that they support callbacks.

#Examples:
Blocking Code

Create a text file named demo.txt with the following content −

Hi, this is the content of demo.txt file!

Create a js file named app.js with the following code −

var fs = require("fs");
var data = fs.readFileSync('demo.txt');
console.log(data.toString());
console.log("node js interview questions");

// Now run the app.js to see the result −

$ node app.js

// Verify the Output.

Hi, this is the content of demo.txt file!
node js interview questions
Non-Blocking Code

Create a text file named demo.txt with the following content.

Hi, this is the content of demo.txt file!

Again open app.js and update with the following code −

var fs = require("fs");
fs.readFile('demo.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
});
console.log("node js interview questions");

// Now run the app.js to see the result −

$ node app.js

// Verify the Output.

node js interview questions
Hi, this is the content of demo.txt file!
#Explanations:
  1. Above two examples explain the concept of blocking and non-blocking calls in node.js.
  2. The first example shows that the program blocks until it reads the file and then only it proceeds to end the program.
  3. The second example shows that the program does not wait for file reading and proceeds to print "Program Ended" and at the same time, the program without blocking continues reading the file.
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. Some people call it to be the 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
What is error first callback nodejs?
  1. 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. 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('my_text_file.txt', function(err, data) {
// If an error occurred, handle it (throw etc)
if(err) {
	console.log('Error Found:' + err);
	throw err;
}
// Otherwise, log the data
console.log(data);
});
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 Application

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 project of node js having different versions etc.

To install or update nvm, you can use the install script using cURL:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
Q:- What is Nodemon?

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server.

It is best tool you can use while developing any node js project. you can install it using NPM.

You can also install nodemon as a development dependency:

npm install nodemon --save-dev
Q:- What is package.json in node js?
  1. package.json is a plain json file which holds all the metadata 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.
  3. The package.json file is normally located at the root directory of a Node.js project.
#Example:
{
"name" : "firstnodeapp",
"version" : "1.0.0"'
	"dependencies": {
		"mypackage": "1.0.0",
		"express": "4.2.x"
	}
}
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.
  5. main - entry point 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
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?
Chaining is a mechanism 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 Module in Node Js?

Module is a set of functionality or javascript libraries encapsulated into 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 Modules
  2. Local Modules
  3. 3rd Party Modules
1. Core Modules:

Node Js Core Modules comes with it's Intallation by default.

You can use them as per application requirments

Load and Use Core Module 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.

These type of modules contain application specific functionality.

Load and Use Local Module with Example:

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

Create a folder common, inside this 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 and use.

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

3rd party modules can be install inside the project folder or globally.

Load and Use 3rd Party Module with Example:

3rd party modules can be downloaded using NPM.

//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:- How To Get Post Data In Node.Js?
/** bodyParser.urlencoded(options)
 * Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
 * and exposes the resulting object (containing the keys and values) on req.body
 */
app.use(bodyParser.urlencoded({
    extended: true
}));

/**bodyParser.json(options)
 * Parses the text as JSON and exposes the resulting object on req.body.
 */
app.use(bodyParser.json());

app.post("/", function (req, res) {
    console.log(req.body.name)
	console.log(req.body.email)
});
Q:- How To Make Post Request In Node Js?

Simple 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: {'key1': 'Hi', 'key2': 'Hello'}
}

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // Print out the response body
        console.log(body)
    }
})
Above code will do GET http://localhost:3000/?key1=Hi&key2=Hello



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: {'key1': 'Hi', 'key2': 'Hello'}
}

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // Print out the response body
        console.log(body)
    }
})
Above code will do POST http://localhost:3000/ with key1=Hi&key2=Hello in the body.
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. Call backs: 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:- Which are best suited IDEs for Node.js?

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

  • MS Visual Studio
  • Atom
  • WebStrom
  • Sublime Text
You may also like - Top 10 Express Js Interview Questions
Full Stack Tutorials

Author | Blogger @FullStackTutorials | View all articles