Must Have NodeJS Interview Questions – Part 2

By | January 16, 2017

This is Part-2 in series of NodeJS Interview Questions, we are trying to explore more intermediate to advanced level concepts related to NodeJS. If you landed to this NodeJS Tutorial directly, we will highly recommend to go through the previous part to understand the beginner level concepts about the technology first, otherwise you can continue reading with this NodeJS article and let us know about your  feedback at the end in comments sections.

We have tried our best to explain all related topics/concepts in detail with the help of practical examples, NodeJS source code and screenshots/diagrams wherever required. This Node.js Tutorial will also be helpful for practically preparing an interview about NodeJS technology.NodeJS Tutorial

NodeJS Interview Questions – Part 2 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.

Advanced NodeJS Interview Questions List

Explain Event Loop Architecture of Node.js?

The applications are processed in a event-loop way using the following steps:

  • When a request or task arrives, it is stored in a event queue.
  • Event queue is then replicated with respective closure, where closure is an inner functions that includes corresponding event along with it’s callback. Event loop helps to run multiple number of event concurrently even though NodeJS Architecture still running in “single-threaded” fashion.
  • Event Loop is a queue of callback functions.
  • The event loop then sends the request to worker thread from a c++ Thread pool, handled by libuv library. All I/O request is performed asynchronously by the threads in the thread pool.
  • Once the thread completes the corresponding I/O request, the associated callback is queued for processing.
  • Event loop executes the callback and return the response.Event Loop Architecture
  • Event loop itself if a single thread running in a single process. Therefore, when an event happen this can run without interruption.

Back to top

How EventEmmiter Works?

Nodejs allow to create custom event using event module and eventemmiter class.

  • Get the reference of EventEmitter class of events Module.
  • Create an object of EventEmitter class by using the reference.
  • Subscribe to event.
    Here, ‘cring’ is the first event, which has register to ‘incomingcall’ listener function. It is possible to register same event to as many as possible functions. Such as:
  • Emit the event.
  • It is possible to count number of listener to any event.
  • Remove any listener.

Back to top

Explain Process Object in Node.js?

‘Process’ object is a global object, always available to Node.js application, therefore, it need not be injected using requires. This object provides the functionality in order to get control of currently running processes. Some other feature of process object are as following:

  • This object is an instance of EventEmitter.

Methods accessible from ‘process’ object:

Method Name Description
process.abort() Abort the currently running process immediately.
process.arch Returns the architecture of the currently running process.
process.argv Returns an array of argument passed at the starting of the Nodejs process.
process.argv0 Stores a read-only copy of the original value of argv[0] passed when Node.js starts. Refers the IPC channel.
process.chdir(directory) Change the current working directory.
process.config Returns the configuration.
process.connected Return ‘true’ if the IPC channel is connected to the process.
process.cpuUsage([previousValue]) Returns user and system CPU time usage of the current process.
process.cwd() Returns the current working directory.
process.env Returns an object defining the environment.
process.emitWarning(warning[, name][, ctor]) Emit custom message.
process.execArgv Returns the set of Node.js-specific command-line options passed when the Node.js process was launched.
process.execPath Returns the absolute pathname of the executable that start the Node.js process.
process.exit([code]) Instructs to exit current process with specified code.
process.exitCode A number that define the code for exiting the process.
process.getegid() Returns the corresponding id of the process.
process.geteuid() Returns the corresponding user  id of the process.
process.getgroups() Returns an array of group id.
process.getuid() Return the id of the user.
process.hrtime([time]) returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.
process.initgroups(user, extra_group) initializes the group access list those are enlisted in /etc/group file.
process.kill(pid[, signal]) Send signal to the process identified by the pid, it may perform something other than killing the project.
process.mainModule Invoke the original main module.
process.memoryUsage() Return the memory used by the Nodejs process computed in bytes.
process.nextTick(callback[, …args]) Adds the callback to the “next tick queue”. Return the pid of the process.
process.platform Returns the information related to operating system platform.
process.release Returns information related to current release.
process.send(message[, sendHandle[, options]][, callback]) Communicates with parent process by sending message.
process.setegid(id) sets the corresponding  group identity of the process.
process.seteuid(id) Sets the corresponding  user identity of the process.
process.setgid(id) Sets the group identity of the process.
process.setgroups(groups) Sets the supplementary group IDs for the Node.js process.
process.setuid(id) Sets the user identity of the process.
process.stderr Returns a Writable stream.
process.stdin Returns a Readable stream.
process.stdout Returns a Writable stream.
process.title Returns the current value of process.
process.umask([mask]) Return file mode creating mask..
process.uptime() Returns a string number of second for while the nodejs process is running.
process.version Returns a json object containing the version for Nodejs.
process.versions Returns a json object containing the version for Nodejs and its dependencies.

Back to top

Explain Cluster Server Object in Node.js?

Usually, a single instance of Nodejs run in a single thread, however, to enable concurrency, it is required to launch a cluster of NodeJS process. This is way to create multiple process, however they all uses the same port. Usually Node.js application run locally on localhost:3000 port. One app runs on one server using single thread on a single process. Using cluster, if the app is running on a i7 having 8 core of processor, then server will be running using 3000 port.

Create an express app by following steps describes here.

  • Create a folder called ‘helloworld’
  • Open command prompt at the new folder  and run ‘ng init’ this will create the package.json and add dependencies for express.
  • Run ‘npm install’. This will install express and required libraries in node_modules folder.
  • Create a file called ‘index.js’ inside ‘helloworld’ folder.
  •  Run ‘node index’. This will start appNode.js Application
  • From browserNode.js App Tutorial
  • Install cluster with command ‘npm install cluster’
  • Install os module ‘npm install os’.
  • Create another file cluster.js.

There are two types of process, if the process is Master, it is possible to copy the same process for number of CPU available in current machine. These copy processes are called worker process.  If any process is not master, they are treated as normal NodeJS program.

Now if we change the index.js as following:

Now if we run the cluster it will give us following output.NodeJS App Output

Therefore, if any given time 400 users hit /login endpoint, without clustering there would be one instance of server to process 400 login request. However, with clustering now for this example, there are 8 instance of the same program, therefore, each of them will serve 50 requests.

How it Works?

  • Child/ worker process is created by triggering the child_process.fork() method. Each worker process can communicate to their parent process through IPC.
  • Master process keep listening for incoming message from worker process. Usually it follows round robin scheduling to receive any incoming message among a number of worker process.
  • Master process can also communicate directly to a particular worker process.

Back to top

This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

NodeJS Course
Take this Course Online Now

What is NodeJS Module? Explain various modules in Node.js? E.g. Request Module | Color Module etc.

What is NodeJS Module?

Modules are developed by the community developers and published under NPM. There are a number of modules. As these modules are not Nodejs built in library, therefore, it is necessary to install these modules using npm install command.

  • A set of codes and file of codes are packaged in a single package and thereby the package is called the module.
  • Every module has its own scope, therefore, a number of modules running at the same time do not conflict with each other.
  • Module can be installed using following command.

    In order to install a module globally

  • Modules can be given global access.
  • Module can be updated using update command

  • In order to use any module in Node.js project, it need to be imported as following:

    module can also be imported from file

    module can also be imported from folder

  • In order to publish any module, it is required to export the module as following:

Node.js Color Module:

This is one of the very popular modules for Nodejs.

Install Color Module as:

NodeJS Color Module

Node.js Request Module:

  • Install request module
  • Declare variable in index.js.
  • Use request module to create action.
  • Make a GET request.
  • Make a POST request.

Back to top

More NodeJS Interview Questions and Answers

What are the followings in Node.js? Karma, Jasmine, Grunt

Karma in NodeJS:

Karma is a testing framework to run JavaScript test case using jasmine test framework.

Jasmine in NodeJS:

It is a behavior driven test framework for testing JavaScript code. This is independent from any other JavaScript module.

Grunt in NodeJS:

This is a command line tool to run task. Grunt has a number of library to deploy the front end code get ready for production.

Here are the steps for building application with Grunt:

Setup Karma and Jasmine to test:

  • Install Karma by using the command.
  •  Install jasmine plugins.
    Alternative is to configure in package.json, adding karma and jasmine as devdependencies as following and run npm install to run all the dependencies.
  • Install command line for karma.
  • Run karma from command line by typing ‘karma start’. Usually karma server will be launched at http://localhost:9876/NodeJS Karma Tutorial
    Alternatively , using package.json and using configuration from karma.conf.js file.
  • The next step is to config karma.

Using Grunt for Deployment:

  • Install grunt-express plugin for express web-server tasks via Grunt.
  • Create ‘Gruntfile.js’.
  • It is possible to describe different server for deployment in Gruntfile.js.
  • Describe the options inside the options tag in Grunt config.
  • Define the task and register.
  • Now if we run express:dev it will start the server on dev environment

Back to top

How we can create HTTPS Server with Node.js?

  • Install connect module.
  • Create a middleware module, to print the message send as the parameter of the request.
  • Create the server app.
  • Run the server with command ‘node index’
  • From http://localhost:8080/ it will shows the message on the web page.

There are several ways to create HTTP request:

  1. Using HTTP Module
  2. Using Express App

Using HTTP Module:

  • Install ‘http’ module.
  • Create a method for a ‘GET’ request.
  • Create a method for POST request.

Using Express App:

  • Create a file called route.js.
    This file will have the list of endpoints.
  • As each of the methods are described in a controller called DBController, therefore create a file called DBController.js.
  • Now from browser, if we call any endpoint defined on route.js and corresponding http request will be executed.

Back to top

How to achieve Concurrency in Node.js?

Eventloop is a single thread running in single process. However there are several ways to achieve concurrency in Nodejs as following:

Asynchronous Programming:

  • Developing application using Asynchronous Programming. async module is very helpful to perform this.
  • An asynchronous function invokes a callback, here cb in the above example which is a function passed as the last argument, this function would be called as the next in the sequence in order to continue the program once the current one has been finished.
  • The threadpool can provides a fixed number of thread. For large scale application where so many operations need to be executed concurrently, the thread pool should have larger number of threads and for small application it is ok if the thread pool has only few threads. It is important to define the number of thread in the thread pool in order to achieve concurrency.
  • Although there is single thread, however multiple process will enable concurrency.

Launching Cluster:

By creating a small network of multiple processes those share main server ports; The details of clustering has been descried above NodeJS Cluster Server Object Interview Questions.

Back to top

What is web scrapping?

Web scrapping is the technology to crawl web page and retrieve information from the wed page. The steps require to extract information using web scrapping are as following

  • We load the page
  • Parse the HTML result
  • Extract the needed data

And the technologies those are required for web scrapping are as following

  • NodeJS
  • ExpressJS: A web framework.
  • Request: make Http Request
  • Cheerio: Implementation of core jQuery functionality for the server. This helps to get value for DOM element
  1. Install express
  2. Install request
  3. Install Cheerio
    In index.js , load express, request and cheerio module
  4. Initialize  express app
  5. Start  server
  6. Create an endpoint go through the IMDB web page or the movie ‘Moana’.

Back to top

How to handle JSON files in Node.js?

These are the following step to handle json file:

Reading JSON File:

  • Import fs module.
  • Read file synchronously.
  • Parse the read content to json object.
  • Get any property of the json file.

Writing JSON File:

Alternatively, it is possible to read json file using require. File extension is optional for this command.

Back to top

Twitter Bootstrap has become the most widely used framework for quickly building responsive websites, and they’re currently launching Bootstrap 4 to the public. This new version of Bootstrap comes with a ton of new features to help you build even better responsive websites. More about this Course Here.
Responsive Design with Bootstrap

This Node.js Interview Questions Part-2 in series of Node.js Tutorial completes all important concepts related to this technology. We will come up with more related technology tutorials to elaborate other related web development concepts. If you feel something really important that is missing, you can contribute by adding your valuable suggestions in comments section.

Top Technical Interview Questions and Answers Series: