Must Have Node.Js Interview Questions

By | January 11, 2017
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest

In this NodeJS Tutorial, we are trying to focus on NodeJS FAQs (Frequently Asked Questions) for beginners to understand the concepts and terminologies related to Node.js in a practical manner. Also, it’s helpful to prepare for an interview with detailed discussion of basic as well as intermediate level Node.js Interview Questions. In next part of this NodeJS Interview Questions Series, we will explore more advanced concepts with detailed and practical examples.NodeJS Tutorial

NodeJS Interview Questions PDF version will be available later for download.

Getting Started NodeJS Tutorial List


Following Node.js & Related Tutorials will be helpful to practically grasp the technology.

NodeJS Interview Questions List

What is Node.js? What are the key features of Node.js?

What is NodeJS?

According to Nodejs.org, Nodejs is a JavaScript runtime or platform which has been built on Chrome v8’s JavaScript engine. This has become the most fast growing and popular platform for building fast and scalable network applications. With the command ‘node’ it starts the google chrome v8 engine and that enables the network to be accessible.

Therefore, it is possible to access the file in the machine or to listen to the network traffic which is not possible using generic JavaScript. Therefore, any action which is possible to perform using ruby on rails or php, now it is possible to perform using JavaScript using Nodejs. Due to the extensively fast growing community and NPM, Nodejs is a very popular open source and cross platform application in order to develop server side and networking applications.

What are the key features of NodeJS?

NodeJS has enable a whole new set of opportunities to JavaScript applications. The main key features for Node.js are as following:

  • Event driven application
  • Non-blocking I/O Model
  • Web applications are more lightweight and efficient.
  • Public package repository, npm.
  • Asynchronous application development
  • Applications are single threaded.
  • High Performance
  • Single threaded but easily scalable

How NodeJS Works?

Node.js application runs on virtual machine v8, which is a high performance JavaScript based engine with a single threaded event loop.
Back to top

How to get and Install Node.js? Briefly explain the steps.

In order to install NodeJS on Windows, we can follow the below steps:

  • Download Node.js from ‘https://nodejs.org/en/download/’
  • For windows, download windows installer.Download NodeJS
  • Run the installer ‘node-v7.2.0-x64.msi’ & Click Next.NodeJS Setup Wizard
  • This will start Installation.Installing Node.js
  • This will complete the installation successfully.NodeJS Setup Tutorial
  • Check version from command line ‘node –version’.NodeJS Version Check Command

For Mac, we have to follow the following steps:

  • Download  ‘node-v6.9.2.pkg’ installar for Node.js by clicking on “Download for OS X” link  from ‘https://nodejs.org/en/download/’.Download NodeJS
  • Click on the ‘node-v6.9.2.pkg’ to start the installation and click ‘Continue’.Installing Node.js on Mac
  • This will start the installation.NodeJS Mac Setup Tutorial

Install NodeJS from Source:

  • Download  ‘node-v6.9.2.tar.gz’ installar for Node.js by clicking on “Download for OS X” link  from ‘https://nodejs.org/en/download/’.
  • Unpack the source by command ‘tar xfz node-v6.9.2.tar.gz’.
  • Move into the folder ‘cd node-v6.9.2’.
  • Configure the project ‘./configure’. This will output:
    ‘configure’ finished successfully.
  • Compile the source with command ‘make’. This will output as following:
    ‘build’ finished successfully.
  • Install build source code using ‘make install’ command.
  • Check version using ‘node –version’ command.

Back to top

What is NPM? What is the need of NPM in Node.js?

NPM is a NodeJS Package Manager used to download, install and manage third party packages.

Here are some featured of NPM are as following:

  • This is a third party package repository.
  • A standard to define dependencies on other package.
  • It provides a Public Registry Service in order to contain all the packages that are developed from NodeJS community and publish in NPM.
  • It provides the standard package descriptor format to specify the third-party module.
  • Since Node version 0.6, NPM is already included in Nodejs , therefore, it is no longer needed to be install separately.
  • NPM has two main modes, global and local. This two are usually the directories to store package. Local directory store the packages those have been installed for the project only. However, global packages are available to all NodeJS applications.
  • It has a Command Line Utility which is installed along with NodeJS in latest version. This command line has ‘install’ ‘update’ ‘uninstall’ command to handle module.

What is the need of NPM in Node.js?

Need of NPM for NodeJS:

  • NPM is required almost every time while using a third party application.
  • It allows to download any library and use that only locally to the NodeJS application instead of installing the library globally.
  • The fast growing repository www.search.npmjs.org is maintained with NPM.
  • Any author can publish any module in NPM for public use.

Node package manager is used to publish any module. Here are the steps:

  • Create a user either in website or using the command. This command will ask for username, password and email.
  • Login as user using the command.
  • Go to the folder of module and Publish the module.
  • Search  module.
  • Unpublish module.

Back to top

How to build a “Hello World” Application in Node.js?

  • Create a folder called ‘hello_world’.NodeJS First Tutorial
  • Initialize the project with command ‘npm init’, this will create the package.json.Package JSON in NodeJSThe project name only support URL friendly character and no longer support Capital letters.
  • This command will create the package.json.NodeJS Application
  • Install all dependencies using the command ‘npm install’.
  • Start the project by running the command ‘node’.Node.js ProjectThis will provide the option to write other things.
  • Lets print ‘Hello World!’.Print NodeJS ApplicationEvery javascript function must return something, this console.log return undefined , therefore , the second line prints ‘undefined’.
  • Create a file called ‘index.js’ inside ‘hello_world’ folder.Index JS File
  • From command line tool run ‘node index.js’.NodeJS Command Line Tool

Back to top

What are the main components of Node.js? Explain all in details.

The main component of Nodejs API is V8 Engine that take care of all object oriented feature and Libuv which is responsible for EventLoop and I/O operations.

V8 Engine:

  1. High performance JavaScript Engine written in C++.
  2. This engine can run stand alone or embedded in JavaScript, such as NodeJS  applications.
  3. Developed by Google Open source community for Google chrome.
  4. NodeJS use v8 as an addons. This provides the mechanism to create object, call function, retrieve information regarding heap.
  5. This works to use C++ code from JavaScript.

The architecture of this engine in Nodejs system is as following:V8 Engine in NodeJS

Libuv:

This is a cross platform library that is responsible for asynchronous I/O operations.

  1. C library mainly used for EventLoop process.
  2. Works as the cross platform abstraction layer.
  3. Provides thread mechanism for more successful asynchronous I/O actions.
  4. The main role of this library is to provide an event loop and mechanism to generate callback based response for I/O operations.

The architecture of this library is as following:Libuv in NodeJS

The I/O operation can be performed over Network I/O such as TCP, UDP, TTY and other protocol. Libub also provides cross platform abstraction layer to perform I/O operation over file system, DNS and user defined methods.   Libuv supports different threading model for processing multiple asynchronous I/O requests such IOCP for Windows, epoll for Linux, kqueue for OSX and other BSDs, event ports for SunOS.

How it Works?

There are two different kinds of abstractions in this library, handle and request.

Handle Request
Long lived object Short lived operations
Can execute operations Is being executed over handle
Callback object notifies handle Is used to write data on handle object
Handle can be either idle or prepare It can also run without handle directly on the event loop

Back to top

Describe in detail about Node.js Processing Model with the help of diagram? Also, How does the Node.js server works?

NodeJS Processing Model:

The processing model of Nodejs follows Multi-Threaded Request-Response model. The following figure describes the steps of this model. Here are some features of this model:

  • This model use Http protocol.
  • Like Http protocol, the response and request of this model are stateless.
  • This model can perform multiple requests concurrently using multiple threads.
  • Following diagram describes Nodejs architecture.NodeJS Architecture

How this Model Works:

  • Nodejs server runs in a infinite loop waiting for client request.
  • Client submits request to the server.
  • There is a thread pool containing limited number of threads. Each client request that requires to perform a blocking I/O operation is processed by an individual thread from the thread pool. The thread is selected by the server for any request. After completing the action requested by the client thread returns the response to the server.
  • If all threads in the pool are busy, incoming client request will be kept waiting.

How does the Node.js Server Works:How NodeJS Server Works

For example, in the above figure:

  • Client A, Client B… n number of clients  submit request Request 1 , Request 2 .. Request n.
  • Requests from clients are received  by server and stored them in Event queue.
  • In the thread pool, there are n number threads.
  • EventLoop picks one after another request from Event Queue.
  • EventLoop picks Request 1
    • Checks if Request 1 needs to perform any blocking I/O operation
      • Lets suppose it does not require any blocking I/O operation
    • EventLoop perform all necessary operations to complete Request 1
    • EventLoop returns response for Request 1 to Client A
  • EventLoop picks Request 2
    • Checks if Request 2 needs to perform any blocking I/O operation
      • Lets suppose it requires any blocking I/O operation such as reading from File system
    • Checks if there is any thread available in thread pool
    • Select an available thread, Thread 1, and assign Request 2 to Thread 1
    • Thread 1 process blocking I/O operation
    • Thread 1 returns response to EventLoop
    • EventLoop returns response for Request 2 to Client B

Back to top

Learn Professional Web Development in AngularJS while building 10 unique Web Apps.
77 lectures, 14.5 Hours Video, All Levels

  • Your First Angular Website
  • Web Template Store
  • myContacts App
  • ngSocial Facebook App
  • Job Directory
  • KnowledgeBase
  • User Authentication App
  • Instagram Gallery
  • PubNub Chat
  • AutoFind

And also we will find Quiz at the end of each application to verify the skill improvement.

What is Node.js MEAN Stack? Mongo DB, Express, AngularJS, Node.JS.

What is NodeJS MEAN Stack?

A full stack web application need a front-end library for data binding and views, a database to store data, a web framework and a web server. Therefore, all these four technologies need to be placed at same place to have a complete web application. The most popular combination of web application development among Nodejs developers is ‘MEAN’, which consists of database MongDB, Web Framework Express, Front-end Framework AngularJs and Web Server NodeJS.

The most significant reason of the popularity of MEAN is from front end to back end every component can be developed using JavaScript.  Other reason of using MEAN are as following:

  • Its cost efficient.
  • The server is very lightweight.
  • MEAN supports 2000 libraries and continuously growing this number.

MongoDB:

  • Install MongoDB.
  • Declare the client variable in index.js
  • Create the connection.

Express:

  • Install express.
  • In index.js, load express, request and cheerio module.
  • Initialize  express app.
  • Start  server.
  • Create an endpoint go through the IMDB web page or the movie ‘Moana’.

AngularJS:

  • Get the Home page from index.js.

NodeJS:

All the server side operations are performed in Nodejs application.

Back to top

Describe the Event Driven Programming in Node.js?

In traditional programming model, each line is executed one after another, therefore, the programming model is blocked until any I/O operation is finished. Later, comes the multi-threading programming model, where if a thread is waiting for blocking I/O operation, another thread take over the CPU and perform its operations. Here programmers do not know which thread is being executed at any moment.

Nodejs is far advanced than traditional  programming model. It  works on Event driven programming model.

Instead of line by line , in event driven programming model, the flow of execution is determined by events. These events are handled or managed by event handler, in case of Nodejs event callback.  Here event callback is equivalent to function which is triggered while something like ‘clicking a button’ or ‘getting response of a database query’ happens.

  • At any given time, at most only one event call back will be running
  • Event callback run until completing the current operation without interruption.
  • Therefore, it is not required extra programming effort to change the shared memory state.
  • Any event if starts can complete without interruption.
  • The main component of event driven programming is eventloop. The main purpose of Eventloop is event detection and triggering corresponding event callback.
  • Example : In traditional system, querying database is as following:
    In Event driving programming model:
    Here, ‘response_avilable’ function has been passed as parameter in query, therefore, when response is available instead of returning the response the query will invoke ‘response_available’ function.
  • In this programming model, the current process will not be blocked  when it is performing I/O.
  • Several I/O can be performed in parallel and when any of the operation is completed , corresponding event callback will be invoked.

Back to top

Briefly explain the followings in Node.js? Debugger, Modules, Console, Streaming, Cluster, DNS, Add-Ons, Domain, Buffer, Global, Net, Call backs, Error Handling, Crypto etc.

There are several concepts available in Node.js as following:NodeJs Tutorial

Modules in NodeJS:

Module provide a view of object oriented programming in NodeJS. Each file is treated by a single module. Any module can be loaded to another or main module. Module can be exported to be used in other modules. Module can be loaded:

  • File as a module
  • Folder as a module
  • Core module can be loaded using just the module name, such as:
    var http= require(‘http’);
  • Modules saved in node_modules folder can also be loaded

NodeJS Debugger:

Node.js can connect to an out-of-process debugging utility using TCP-based protocol and built-in debugging client. NodeJS debugger is a full feature debugger. Any node need to be started with ‘debug’ keyword as following:NodeJS Debugger

In order to add break point, it is required to add ‘debugger’ in the source code on expected line.

Streaming in Node.js:

Streaming in NodeJS is performed by creating an instance of ‘stream’ abstract interface using stream module. NodeJS provides a number of stream object each of them are instace of ‘EventEmitter’ class and stream object can be readable, writable or both. Stream object can work on either string or Buffer object. In order to work with other type of JavaScript object, stream is switched to’Object Mode’.

Node.js Console:

This is a normal debugging console. It is possible to configure a file as the console , in that case the console is synchronous, otherwise each instant of console is asynchronous.

Method Name Action
console.assert(value[, message][, …args]) Simple assertion test
console.error([data][, …args]) Print the error
console.info([data][, …args]) Print information
console.log([data][, …args]) Prints ‘stdout’ and a new line
console.time(label) Start timer
console.trace(message[, …args]) Print stderr
console.warn([data][, …args]) Call console.error()

Add-Ons:

These are dynamically shared object, mainly written in C++/ C. like other modules, any Add-ons can be loaded using ‘require’. The primary role for Addons is to provide interface between java script and c/c++ libraries.

V8: This is a C++ library used to create object, call function, allocate memory and other action need to be performed by V8 engine.

Libuv: The processing model of NodeJS EventLoop, it’s worker thread and other synchronizes behavior through out the application process have been implemented using this C library. This add ons also act as the cross platform abstraction layer.

Buffer:

TypedArray has been introduced in EC6 in 2015, before that JavaScript has no way to deal will octect data stream, therefore, buffer has been introduced in Nodejs for the first time in order to read a write binary data just like as file reading and writing.

  • ‘Buffer’ class is global within Nodejs application scope.
  • An instance of ‘Buffer’ class is similar to fixed –sized array of integer.
  • Each instance of the Buffer class corresponds to allocated memory outside V8 heap.
  • The array is not resizable as it is fixed size.
  • Each of the integers in  a buffer  instance is represented by  a byte so the value of each integer is limited to 0 to 255 (2^8 – 1).

Create Instance of Buffer:

Reading Binary Using Buffer:

writing Binary using Buffer:Writing Binary Using Buffer

Line 1 , create a buffer of size 20. Then on line 2 write ‘Hello world’ with encoding utf-8. This will return 11 as it has written 11 bytes. We still has 9 bytes left so write something else, ‘Nodejs’ with another 6 bytes.NodeJS Buffer Output

Now read the instance ‘buffer’.Buffer.toJSON

Buffer.toJSON() returns the ASCII value stored in the memory and tostring() returns the actual string that has been written.

Domain:

Domain is used to work with multiple I/O operations as a single group. However, this has been pending to be deprecated.

Global:

Global objects are available in all modules. For example, Buffer class, require method, process object, console object etc are global to all Nodejs module.

Net:

This is an asynchronous network wrapper. This module provides function to create TCP local server and client. All network related operations such as creating connection, read byte from stream and write to stream etc are performed using this module.

Callback:

In NodeJS callback is very important for asynchronous programming. It is equivalent to a function call in asynchronous programming.  All the Node.js libraries supports callback. At the end of current task callback is called.  The main purpose of using callback is to provide non blocking I/O operations,  therefore NodeJS application can support multiple operations while reading a large file.

Error Handling:

Try –catch block is supported in Node.js in order to handle error. Another supporting library is assert to check true value for any variable and throw exception.

Cluster:

This is a single instance of NodeJS server. In order to run multiple process, cluster can be lunched. There are master process and worker process created by the master process. Master process keeps listening for new connection, and then distributes it either in round robin fashion among worker process or only to interested worker process instead of all worker processes.

Crypto:

Nodejs provides a number of encryption decryption  library through crypto module. Diffie-Hellman ,Elliptic Curve Diffie-Hellman (ECDH)Elliptioc curve cryptography (ECDH) key exchange, signature generation, signature verification and authentication is possible using this module.

DNS:

This class is responsible for finding the server for given name. There are two different ways to perform name resolution and find the server for given address name. One is to use the underlying operating system’s facility to perform name resolution and other is without using the facility provided by the   underlying operating system. There are  a number of functions to resolve the address name.

Back to top

Explain REPL(READ, EVAL, PRINT, LOOP) in Node.js?

REPL is a standalone module, which can be used in another application or can be used as a standalone program.

Flow of work for REPL Engine:REPL in NodeJS

The workflow starts as following

READ:  Read user input and parse it using javascript. Convert the input to corresponding data structure and store it in memory

EVAL: Executes the data structure using user defined function.

PRINT: Returns the response.

LOOP:  Loop back to ready state in order to read user input until user press ‘CTRL + C’ twice.

REPL Commands

REPL Commands in NodeJS

Back to top

You can continue with next part having more intermediate to advanced Node.js Interview Questions in this Web Developer Interview Questions Series.

Top Technical Interview Questions and Answers Series:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest