NodeJS Interview Questions

Prepare well and walk out with a sure job offer with these top Node.js interview questions and answers. We have compiled the common Node.js interview questions along with the best answers that will help you crack your interview and land the best job as a Node.js Developer. The following Node.js interview questions will help you prepare for technical interviews and online selection tests and answer questions on the basics of Node.js, its features, npm and its components.

  • 4.5 Rating
  • 40 Question(s)
  • 45 Mins of Read
  • 9654 Reader(s)

Beginner

NodeJS is an environment to execute JavaScript code on a web server. This allows us to write server-side code using JavaScript. NodeJS is free, open-source and is available for all major platforms including Windows, Linux and Mac. NodeJS is built using Chrome’s V8 runtime engine.

V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Google Chrome, the open source browser from Google, and in Node.js, among others. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. V8 can run standalone, or can be embedded into any C++ application.

I/O refers to input/output. It can be anything ranging from reading/writing local files to making an HTTP request to an API. Blocking IO simply means that while the server is processing an IO request for a client, if it receives another, the new request (and all requests that follow) with the blocked until the first request is completed. This is really inefficient and requires multi-threading to be able to process multiple requests simultaneously.

Node is all about non-blocking, asynchronous architecture. This means any activity taking a long time to finish, such as file access, network communication, and database operations, are requested and put aside until the results are ready and returned via a callback function.

Using a non-blocking request, you can initiate a data request for another user without waiting for the response to the request for previous users. You can initiate both requests in parallel.

This non-blocking I/O eliminates the need for multi-threading since the server can handle multiple requests at the same time.

Asynchronous I/O is a form of input/output processing that permits other processing to continue before the transmission has finished. In the simplest form, line #10 of your code can be executed before line#7 is done executing.

It simply means that more than one processes can be executed in parallel. If some job, for example, read a large file, is taking longer, you do not want to hold everything else in your application/program/application as well. Asynchronous code allows you to carry on with the execution normally and when the long-running task finishes, you execute the pieces that strictly depend on the output of the operation. The result of each operation will be handled once the result is available.

In asynchronous programming, we create functions that do not wait for functions above them to be completed first. To keep things simple and organized, we use promises and callbacks.

NPM stands for Node Package Manager. NPM is installed with NodeJS. It allows us to manage the Node packages within our project in a simple and easy manner. 

The main goal is automated dependency and package management. This means that you can specify all of your project's dependencies inside your package.json file, then any time you (or anyone else) needs to get started with your project they can just run npm install and immediately have all of the dependencies installed. On top of this, it is also possible to specify what versions your project depends upon to prevent updates from breaking your project.

To install a package using NPM, we need to issue the command

npm install <package-name> [flags]

There are several optional flags that we can use to configure how the package is installed.

As the name suggests, REPL (Read Eval print Loop) performs the tasks of – Read, Evaluate, Print and Loop. The REPL in Node.js is used to execute ad-hoc Javascript statements. The REPL shell allows entry to javascript directly into a shell prompt and evaluates the results. For the purpose of testing, debugging, or experimenting, REPL is very critical.

It is a quick and easy way to test simple Node.js/JavaScript code. It also allows a way to developer CLI applications.

Node.js includes a debugging utility called debugger. To enable it, start the NodeJS with the debug argument followed by the path to the script to debug.

Inserting the statement debugger; into the source code of a script will enable a breakpoint at that position in the code.

The package.json file is core to the Node.js ecosystem and is a basic part of understanding and working with Node.js, npm, and even modern JavaScript. The package.json is used as a manifest about applications, modules, packages, and more - it's a tool to that's used to make modern development streamlined, modular, and efficient.

Every NodeJS Package or Module should have this file in the root directory to describe its metadata in plain JSON Object format. We should use same file name with same case “package” and same file extension “*.json”.

  • ExpressJS
  • SocketIO
  • Browserify
  • Request
  • PM2
  • Bower
  • PassportJS
  • Async
  • Gulp
  • Grunt

Mongoose (used for MongoDB in NodeJS)

Error-first callbacks are used to pass errors and data as well. You have to pass the error as the first parameter, and it has to be checked to see if something went wrong. Additional arguments are used to pass data.

Here is an example.

fs.readFile(filePath, function(err, data) {  
   if (err) {
     // handle the error, the return is important here
     // so execution stops here
     return console.log(err)
   }
   // use the data object
   console.log(data)
})

No, NodeJS is an environment that allows us to execute code written in JavaScript on a server. This simply enables developers to write server-side code using JavaScript.

JSON stands for JavaScript Object Notation. It is a wildly popular data exchange format and has replaced XML largely. It is very simple and uniform and can be read and written using any text editor. Here is an example of a simple JSON object.

{ 
     "name": "Sara",
     "age": 23,
     "gender": "Female",
     "department": "History",
     "car": "Honda"
}

As you can see, it is simply a collection of key-value pairs. It can even represent more complex datasets and can even stored nested information. 

JSON has enabled JavaScript developers to quickly construct APIs and foster interoperability at scale -- a key objective for Node.js coders.  

var http = require('http');
var server = http.createServer( function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World!');
});
server.listen(8080); 

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 can not be imported using require() in Node application directly. To install a Node project globally use -g flag.

Example command: npm install express -g

By default, npm installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require(). To install a Node project locally following is the syntax.

npm install express

Advanced

The event loop is in the heart of Node.js / Javascript - it is responsible for scheduling asynchronous operations.

The event loop is what 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. To really understand event loop, you must first understand the phases involved in the event loop and also what happens in each phase.

  1. Timers - Everything that was scheduled via setTimeout() or setInterval() will be processed here.
  2. IO Callbacks - Here most of the callbacks will be processed. As all userland code in Node.js is basically in callbacks (e.g a callback to an incoming http request triggers a cascade of callbacks), this is the userland code.
  3. IO Polling - Polls for new events to be processed on the next run.
  4. Set Immediate - Runs all callbacks registered via setImmediate().
  5. Close - Here all on(‘close’) event callbacks are processed.

The event loop as a process is a set of above-defined phases with specific tasks that are processed in a round-robin manner. There is only one thread that executes JavaScript code and this is the thread where the event loop is running. The execution of callbacks is done by the event loop.

If the application is idle, which means that there are no pending tasks (Timers, callbacks, etc), it would not make sense to run through the phases with full speed, so the event loop will adapt to that and block for a while in the polling phase to wait for new external events coming in.

Callbacks in the general definition are just functions that you pass to other functions. It is called at the completion of a certain task. Looks at the following example.

const shopping = function order(amount, callback) {
payAmount();
saveOrderToDatabase();
callback("Order Received");
}

In the above code, the order function received two arguments, The first one is the amount and the second one is the callback which is a function which will be executed after the order function is done with everything else. In this case, it confirms that the order has been received. Instead of being called immediately, the callback function is called at a certain point in the future.

Callbacks are used widely in NodeJS. In fact, all NodeJS code is a callback in some way.

Interestingly, if you pass a function to another function as a parameter, you can call it within the function when you are finished with your job. No need to return values, only calling another function with the values.

It is definitely possible to manually download your libraries, copy them into the correct directories, and use them that way. However, as your project (and list of dependencies) grows, this will quickly become time-consuming and messy. It also makes collaborating and sharing your project that much more difficult.

NPM makes sure that a record of every dependency that your project is using is maintained ( in the package.json file) and whenever you or a co-workers needs, they can create an exact replica of the dependencies with a simple command. NPM connects to the world’s largest package repository called npmjs.com to download the required packages.

Callback Hell, also known as Pyramid of Doom, is an anti-pattern seen in the codes of programmers who are not wise in the ways of asynchronous programming.

async1(function(){
    async2(function(){
         async3(function(){
             async4(function(){
                 ....
             });
        });
     });
});

It consists of multiple nested callbacks which makes code hard to read and debug. It is understandable how one might unknowingly get caught in Callback Hell while dealing with asynchronous logic. If you are not expecting your application logic to get too complex, a few callbacks seem harmless. But once your project requirements start to swell, you will quickly find yourself piling layers of nested callbacks. That’s the callback hell.

In simple words “A promise is a word taken for some action, the other party who gave the promise might fulfill it or deny it”. In the case of fulfilling, the promise gets resolved, and in another case, it gets rejected.

A promise can be created in our JavaScript code (and therefore in NodeJS). Or else it can be returned from an external node package

Any promise that performs async operations should call any one of the two methods resolve or reject. The code logic should take care of when and where to call these functions. If the operation is successful, pass that data to the code that uses that promise, otherwise pass error

The code which uses a promise should call then function on that promise. It takes two anonymous functions as parameters. The first function executes if the promise is resolved and the second function executes if promise is rejected.

console.log("first");
setTimeout(function() {
     console.log("second");
}, 500);
console.log("third");

The sequence of operations will be following.

first

third

second

The setTimeout method takes a callback function which will only be executed after 500 milliseconds. So by the time the second log prints, the third log is already printed. The code is asynchronous in nature and therefore the code will keep on executing without waiting for the setTimeout to return.

Within a web browser such as Chrome, declaring the variable i outside of any function’s scope makes it global and therefore binds it as a property of the window object. As a result, running this code in a web browser requires repeatedly resolving the property i within the heavily populated window namespace in each iteration of the for loop.

In NodeJS, however, declaring any variable outside of any function’s scope binds it only to the module’s own scope (not the window object) which therefore makes it much easier and faster to resolve.

Asynchronous literally means not synchronous. We are making HTTP requests which are asynchronous, means we are not waiting for the server response. We continue with other block and respond to the server response when we received.

The term Non-Blocking is widely used with IO. For example, non-blocking read/write calls return with whatever they can do and expect caller to execute the call again. Read will wait until it has some data and put calling thread to sleep.

libuv is a multi-platform support library with a focus on asynchronous I/O. It was primarily developed for use by Node.js, but it’s also used by Luvit, Julia, pyuv, and others.

When the node.js project began in 2009 as a JavaScript environment decoupled from the browser, it is using Google’s V8 and Marc Lehmann’s libev, node.js combined a model of I/O – evented – with a language that was well suited to the style of programming; due to the way it had been shaped by browsers. As node.js grew in popularity, it was important to make it work on Windows, but libev ran only on Unix. libuv was an abstraction around libev or IOCP depending on the platform, providing users an API based on libev. In the node-v0.9.0 version of libuv libev was removed.

Some of the features of libuv are:

  • Full-featured event loop backed by epoll, kqueue, IOCP, event ports.
  • Asynchronous TCP and UDP sockets
  • Asynchronous file and file system operations
  • Child processes
  • File system events

Express is a fast, un-opinionated minimalist web framework for NodeJS. ExpressJS is a web application framework for NodeJS. It provides various features that make web application development fast and easy which otherwise takes more time using only NodeJS.

ExpressJS is based on the NodeJS middleware module called connect which in turn uses http module. So, any middleware which is based on connect will also work with ExpressJS.

ExpressJS allowed development of web server with NodeJS very easy and convenient. It allows us to define different routes that the web server can handle. It includes various middleware modules which you can use to perform additional tasks on request and response. ExpressJS is easy to integrate with different template engines like Jade, Vash, EJS etc.

SocketIO is a bi-directional realtime event-based communication library. It consists of a server package for NodeJS and a client-side library. It is built on top of EngineIO. It abstracts many transports, including AJAX long-polling and WebSockets, into a single API. It allows developers to send and receive data without worrying about cross-browser compatibility.

SocketIO has played an important role in the popular adoption of NodeJS by making WebSockets both accessible and reliable. Version 1.0 represents a major step in its evolution and the extraction of EngineIO has opened up some interesting possibilities for the NodeJS ecosystem.

PassportJS is a simple, unobtrusive NodeJS authentication middleware for NodeJS. PassportJS can be dropped into any Express.js-based web application.

Passport recognizes that each application has unique authentication requirements. Authentication mechanisms, known as strategies, are packaged as individual modules. Applications can choose which strategies to employ, without creating unnecessary dependencies.

By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked. If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

A middleware is basically a function that will the receive the Request and Response objects, just like your route Handlers do. As a third argument you have another function which you should call once your middleware code completed. This means you can wait for asynchronous database or network operations to finish before proceeding to the next step.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

ESLint is an open source project originally created by Nicholas C. Zakas in June 2013. Its goal is to provide a pluggable linting utility for JavaScript.

Besides checking style, linters are also excellent tools for finding certain classes of bugs, such as those related to variable scope. Assignment to undeclared variables (these leak into the global scope, contaminating it and possibly causing very difficult to find bugs) and use of undefined variables are examples of errors that are detectable at lint-time.

The main idea of Node.js: use non-blocking, event-driven I/O to remain lightweight and efficient in the face of data-intensive real-time applications that run across distributed devices. What it really means is that Node.js is not a silver-bullet new platform that will dominate the web development world. Instead, it’s a platform that fills a particular need. It is obviously not suitable for all kinds of implementations.

Compared to traditional web-serving techniques where each connection (request) spawns a new thread, taking up system RAM and eventually maxing-out at the amount of RAM available, Node.js operates on a single-thread, using non-blocking I/O calls, allowing it to support tens of thousands of concurrent connections held in the event loop.

So, you might want to use NodeJS where there are more users with less per user overhead. For example, a chat application. NodeJS is widely used in developing APIs as well. When it comes to heavy computation, Node.js is not the best platform around. No, you definitely don’t want to build a Fibonacci computation server in Node.js. In general, any CPU intensive operation annuls all the throughput benefits Node offers with its event-driven, non-blocking I/O model because any incoming requests will be blocked while the thread is occupied with your number-crunching.

An LTS (Long Term Support) version of Node.js receives all the critical bug fixes, security updates and performance improvements.

LTS versions of Node.js are supported for at least 18 months and are indicated by even version numbers (e.g. 4, 6, 8, 10). They're best for production since the LTS release line is focussed on stability and security, whereas the Current release line has a shorter lifespan and more frequent updates to the code. Changes to LTS versions are limited to bug fixes for stability, security updates, possible npm updates, documentation updates and certain performance improvements that can be demonstrated to not break existing applications.

The difference between process.nextTick() and setImmediate() is that process.nextTick() defers the execution of an action till the next pass around the event loop or it simply calls the callback function once the ongoing execution of the event loop is finished whereas setImmediate() executes a callback on the next cycle of the event loop and it gives back to the event loop for executing any I/O operations.

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

  1.  Use Generators.

Generators are lightweight routines, they make a function wait and resume via the yield keyword. 

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

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.

Buffer class is a global class and can be accessed in application without importing buffer module. A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.

Description

Nodejs is a server-side technology and is popular among the Mean stack developers. Node.js developers are offered fruitful salaries around $102,500 per year. If you are planning to shape your career as a Node.js developer, then these interview questions for node js will definitely help you in shaping your career.
 
The node js interview questions covered here will surely help you in clearing the interview with full confidence. Interview questions on node js have been written by our experts. Read and practice these node js programming interview questions before going for an interview. These sample node js interview questions will help you to crack your interview and obtain a dream career as a Node.JS Developer.

Here, we have listed the most popular node js interview questions and answers for experienced and freshers. There could be many other interview questions on node-js that you need to practice to clear the interview. 
 

Levels