Author Archives: Web Development Tutorial

Top 20 MongoDB Interview Questions

In order to build a MEAN-based web application, MongoDB plays the key role along with AngularJS, NodeJS and Express. In this MongoDB Tutorial, our focus is to start learning MongoDB from beginning. This article can also be taken as Part-1 in Series of MongoDB Interview Questions with practical and detailed answers. We will start will very basic questions about MongoDB including What it is? How to create a NoSql database using MongoDB and then moving to more advanced topics.MongoDB Interview Questions

Getting Started MEAN Stack Tutorial Series

We already have covered other components of Full Stack JavaScript by cover the followings:

MongoDB Tutorial PDF version will be available later for download.


MongoDB Interview Questions Tutorial – From Beginner to Professional

What is MongoDB, explain MongoDB as Nosql database in detail and how it is different from relational database?

MongoDB is cross platform document based database. It is a NoSql database and very different from traditional relational databases like Oracle, MS SQL, MySQL etc. MongoDB provides high availability, high performance and easy scalability. Easy scalability means it is very easy to scale MongoDB database in comparison of relational databases.

MongoDb works on the concept of document and collections. We will go through each and dig down in detail. Lets first quickly understand what NoSql databases is?

What is NoSql database?

NoSql referred as non-sql databases that enables us to store and retrieve data in non-tabular format. When we say non-tabular format then we want to say there will no tabular database like relational database. So the data will be present in non-tabular formats.

Now lets understand what document and collection is, with respect to MongoDB, which are backbone of this database.

Document:

Document in MongoDb is a set of key value pairs. Each document has schema associated with it. These schema are dynamic in nature. MongoDb stores documents as BSON data, that stands for Binary representation of JSON data. BSON is binary serialization format that is used to store JSON data. As we discussed above MongoDb documents are key-value pair set and have the following structure.

Value can be any of the datatype that BSON supports. BSON supports number of datatypes.

Collection:

In MongoDb collections are used to store documents. Collections can be taken as tables in relational databases.

If we compare MongoDb with relational databases, then Table of relational database is called Collection in MongoDb, Row of relational database is document in MongoDb, Column is called field here and joins are referred as embedded documents.

Below is the simple example of a document:

In the example above we have created a simple document, that contains information about a employee.

_id is the identity of document, it is basically a hexadecimal value, that ensures uniqueness of a document. As we can see employeeId is type of int, address is String, technlogyKnown is array of Strings. In the education field, there is date field. There are verify of datatype that MongoDb supports.

Although there are few restrictions with key or field names:

  • Field names cannot be null.
  • Field names cannot contain dot (.)
  • Field names cannot start with dollar sign($).

_id is reserved for primary key in MongoDb.

Back to top

What are key advantages of MongoDB?

Key Advantages of MongoDB:

Following are  the  key advantages of using MongoDB i.e. a NoSQL database:

  • Removal of Complex Joins:
    unlike relational databases where tables are referentially connected, and to retrieve data, we need to build a complex query using joins. To write such complex queries one need to have a very good command on db. In MongoDb you need not to write such complex queries, all you need to do is to design a good schema that will contain these documents
  • Easy to scale:
    MongoDb enables us to horizontal scale the database. For this purpose there is technique called sharding is used.
  • Clear structure of object:
    In MongoDb if there is good schema defined, there will be a very clear structure of object and one can easily identity the collection and document structure.
  • Failover:
    Failover is automatically handled, that means , in a cluster if a node goes down which is primary, secondary node automatically comes up.

Back to top

Explain with steps how to configure MongoDB in details, attach code snippet and diagram whereever applicable?

To configure MongoDb on our local machine or on some remote machine, first we need to download the extract of MongoDb from MongoDb official website (https://www.mongodb.com/download-center).

Based on the operations system, we need to download the extract or installation file. Make sure you are downloading the latest version of MongoDb.

One you have downloaded the extract from web. Now we need to install and configure it. Here we will be talking about installation and configuration on Windows operating system. First we need to install the extract file that is downloaded from MongoDb official site.

First we need to create two folders data and under data we need to create db folder. Following will be commands for the same.

Here I am creating these two folders in C drive.MongoDB Tutorial

Once we have created these two directories, we need to navigate to bin folder of mongodb insallation directory. After that we need to run the command as below :

MongoDB Installation TutorialIf every things goes fine then, console will show waiting for connections, which indicates that mongodb has been installed and configured successfully.MongoDB Configuration

Now to run MongoDb, open console in other console. And run mongo.exe command.MongoDB Commands

In the snap above, we have connected to mongodb and created a test record and executed a find command which ensures that mongodb has been installed and executed successfully. These find and save commands will be covered in next questions.

Back to top

Explain how to define schema in MongoDB with example, how these schemas are different with RDBMS schema, explain with example?

Data in MongoDb is stored in form of key , value pairs. And a set of these data is called document in terms of MongoDb. Each document has a flexible schema. Documents don’t need to have the same set of fields, structure. MongoDb provides such flexibility.

While designing mongodb schema , there are few things that we need to keep in mind.

  • Objects that are intended to use together, should be kept in a document. If not then its better to separate these objects in different documents.
  • Schema should be optimized for the queries or use cases that are most frequently used.
  • Joins can be used but make sure to use joins while writing data on data base not while reading data from database.
  • Schema should be designed particularly on the requirement and should be flexible.

Lets try to understand it with an example and we will compare the schema of MongoDb with RDBMS schema.

Lets suppose we are designing a online shopping web application. Which have the following requirements:

  • There will be multiple items with some tags.
  • Each item will have unique name and description.
  • Each item will have information about seller, name and id.
  • Each item will have then number of comments given by users with likes and dislikes
  • On each item can have multiple comments or no comments.

Lets see how RDBMS schema will look like:MongoDB Schema Example

As we can see, as per our requirement, there will three tables, which will have relation to each other. There will be an item table with some fields, which will have connected with tags table. Tags table will have referential relation with item table, Same goes for comments table, which will also have referential relation with item table.

Now lets try to achieve the same with MongoDb. Lets design schema for the same in MongoDb. MongoDb schema will have a well defined collection, which will adhere to the requirement. Below is the schema for the same.MongoDB Schema Tutorial

Now if we compare both the schemas, we can see in relational database we need to create three different tables with referential relation, where as in MongoDb the same can be achieved by just a well defined collection.

Back to top

Explain how to create databse in MongoDB?

To create database in MongoDb, ‘use’ command is used. This command is used to create database in MongoDb. It will create database if doesnot exists if exists it will return the existing database name. In MongoDb the default database is ‘test’. If we don’t create any database the collections will be stored in the default test database.

Syntax of this command is as follows:

Lets try to understand this command with example :

Suppose we need to create database with name BookStore. Syntax for the same will be:Create MongoDB DatabaseLets say we want to check the list of database, we will use the show dbs command. Below is the syntax for the same.MongoDB Database Tutorial

Wondering ! why our newly created database is not in the list. The answer is the database should have at least one document stored. Once our db will have records or documents, it will be displayed in the list.

Lets create a record in db and try to check the same with show dbs command.Show DBS Command

Here we have created a document and stored a record in this. Now if we check with the same command , as you can see our newly created database BookStoreDb is top on the list.

If you want to  check on which database you are currently on, db command will be used, below is the syntex:BookStoreDB in MongoDB

Back to top

What are collections in MongoDB, explain with example?

Collections in MongoDb:

Collections in MongoDb are similar to tables in relational databases. Collections contains the documents in MongoDB. These documents may or may not be in the same structure.

To create collections in MongoDb createCollection is used. Syntex to create collection in MongoDb is :

This method takes two parameters, name and options. Name is implicit that is name of collection that is being created. Options is the optional parameter and of document type. Which will have configuration related to document.

Below are the configuration options for collection:

  • autoIndexID, which is Boolean type of field, optional parameter, true means index should be creted on the _id. Default value is false.
  • max , number type of field, optional parameter, indicates max number of documents allowed in the collection.
  • capped , Boolean type of field, optional parameter, if true creates a capped collection.
  • size , number type of field, indicates the size of capped collection.

Lets try to understand with creating a collection:Creating Collections in MongoDB

Here we have created a collection with ComputerProgramming name.

Now lets check the created collection. To list the collections in MongoDb, the following command will be used:

Lets try it:Show Collections

As we can see it has the list of collections and our newly created collection(ComputerProgramming) as well.

Now lets create collection with the optional fields:MongoDB Collections Tutorial

As we can see, MongoDb has created collection with the options provided. Lets try to list collections now, it should both the collections that we have created.MongoDB Collections List

In MongoDb, we don’t need to explicitly create collections. MongoDb automatically creates the collections once we insert document. Lets try to create  a collection not with createCollection command, but directly inserting records.Show Collections in MongoDB

As you can see now, we have directly inserted document in ScienceBooks collection, which was not present. MongoDb automatically created ScienceBooks document and inserted records in it. In show collection command now it has the collection, ScienceBooks. It is all about collection and database in MongoDb.

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.

Intermediate to Advanced MongoDB Interview Questions Tutorial

How to create backup and restore the MongoDB database? Explain with example?

Backup is basically to create a dump of existing database, that can be restored as and when required. As in relational database, MongoDB also provides the functionality to create dump of database and use it dump when required, with restoring functionality.

Creating Backup with MongoDB:

In order to create backup of existing database in MongoDB, MongoDB provides mongodump command. Using this command we can create dump of database. This command will create the entire dump of your database in the dump directory.

There are few options available with this command, that can be used as needed. Following are the options available with this command:

Now lets create a backup of db. For this we need to traverse to bin directory of Mongodb installation. Once we are on the bin directory on command prompt, run ‘mongodump’ command. This command will create a dump directory in bin directory of MongoDB. And it will keep all the backup in this folder. Lets try to run the command:MongoDB Tutorial Taking Dump

As we can see, it has created dump of our database successfully. Let’s traverse through the folder structure and try to see dump folder contents:MongoDB Dump Folder Structure

So this will be the folder structure of dump folder. It has created the dump and as we have created BookStoreDB, we can see the dump of that db as well.

Restore Backup with MongoDB:

Similarly to restore the backup, MongoDb comes up the mongorestore command, this command will restore the backup created.

To run this command we need to traverse to bin directory from command prompt and once we are on bin directory, we need to run this command. Lets try to run this command and see:MongoDB Restore Tutorial

As we can see, our created backup has been restored with this command.

This is all about backup and restore database in MongoDb.

Back to top

What are CRUD operations and how these crud operations are performed in MongoDB? Implment a proper example with PHP to connect with MongoDB and perform all CRUD Operations.

CRUD operations in database terms stands for Create, Retrieved, Update, Delete. All databases irrespective of Sql or Non sql have these functions in place. We will go through one by one with example in MongoDB and PHP.

MongoDB and PHP Example:

Like relational database connection, first we need driver to connect. For this we need to download driver from official site. Once we are done with download of driver, we need to put the dll file that is php_mongo.dll in ext directory. After adding the file to ext directory in php.ini file we need to add a line that will have a reference to this dll file.

Once we are done with this, we are set to go with our php code that will create database connection and perform these operations. Lets start with connecting to db and creating a collection:

The code above will create connection to MongoDb database instance. It will take the database which is BookStore in our case. Once we have selected BookStore database, we are good to go with creating a collection. createCollection() function will create a collection in our case we are taking collection as ScienceBooks. If everything goes fine, we will able to see the below on console.MongoDB and PHP Tutorial

Once our collection is created, we are good to go with performing CRUD operations.

Lets start with C, that is create a record. To create a record, insert() method is used in MongoDb, that takes document as argument, which contains the data that needs to be inserted.

Lets suppose in our bookstore, we need to create records for ScienceBooks, that will have BookName, BookAuthor, ISBN fields. Now are already created collection for ScienceBooks, all we need to do is to create a records underneath it. Below is the example to achieve the same.

Lets try to understand the above code, we have already created a collection. Now we need to create a record underneath it, what we have done is we have created a record with the fields, for example purpose and make code readable I have hardcoded the values, which will never be in real world scenario, values will be dynamic and not static. We can add as many records in the array as we want. Once our array is ready with the records, all we need to do is to pass it to insert method. If everything goes fine, the below message will be displayed on our console.CRUD Operations with MongoDB

Now lets come to R, that is for read operations in CRUD. Lets try to find out the record that we have just created. To read or in other words to find document in MongoDb term, find() method is used. Lets simulate from code and try to retrieve record from BookStore database.

In the above code fragment what we have done is, we have fetched records from ScienceBooks collection, and print BookAuthor. So basically find method will return me list of all records, once I get list of records, we need to traverse through is to get records and print the required value from key associated with it. Like in the code above we have printed book author, which was stored with BookAuthor key.

In crud operations, U stands for updating records in the database. In MongoDb, updations on a record is done though update() method. Just now we have created a records in BookStore database and in ScienceBooks collection. Now we need to updated it through and lets suppose we need to update ISBN number which was by mistake entered incorrect. Below is the code for the same:

In the example above, we have just updated the ISBN number that was stored incorrect, we have updated to correct one and finally printed the updated entry. After successful run of the above code fragment we will get ISBN number as 45387984.

Finally lets come to D, that is delete operation in CRUD. To delete a record or in MongoDb terms, to delete a document from database, remove() method is used. Lets try to remove the document with ISBN key as 45387984, which we have just updated:

In the code fragment above we have deleted a record with ISBN key as 45387984. Now if we add the fetch code here and try to traverse over it, it will print nothing. Since the document is no more in the database.

Back to top

What are indexes with respect to a database, how indexing is performed in MongoDB, explain with example?

Indexes are basically a special kind of data structure in database term, which helps to optimize the query performance. Basically while searching in MongoDB , in a normal search, let suppose you have millions of documents in a collection, then for a particular document search, MongoDB have to search through each and every document in the collection which is time taking. While having indexes in place, MongoDB will limit the search with help of these indexes.

In principle Indexes stores the value of a specific field or a set of fields ordered by the value of the field. Since the data is partial, it becomes easier to read this data.

Creating Indexes in MongoDb:

To create index in MongoDb, createIndex method is used. Below is the syntax to create index in MongoDB.

Collection name will the name of collection. Key will the key on which index needs to be created, next parameter indicates that the key on which index to be created, it’s values should be in ascending or descending order. 1 indicates that values will be in ascending order, whereas -1 indicates that values will be descending order.

Lets take an example, Suppose we have a BookStore database which have collection as ScienceBooks. Document in this collection looks as:

Lets assume we need to create index on BookName field. Below will be code for the same:

The above code will create a index on BookName field and the values will be in sorted in ascending order.

Indexes can be created on more than one fields, that mean, if we want to add other keys in index, we can and the index will be created on both key fields. Lets try to run the command and create the index:MongoDB Indexes Tutorial

Lets try to understand the output now :

  • numIndexesBefore indicates that how many indexes are present before this command is executed.
  • numIndexesAfter indicates that how many indexes are present after this command is executed.
  • ok represents that the operation was successful and indexes are successfully created in database.

Lets say we want to know how many indexes are there in databases and on what keys they are, getIndexes() command is used. Below is the syntax for the same:

Lets try to run the command and try to get the list of indexes present in our ScienceBooks collection:MongoDB Indexes Interview Questions

As we can see there are two indexes displayed in the output, one is on _id field and other is on OrganicChemistry field. ‘1’ , as we have discussed, indicates that field values are sorted in ascending order.

Now lets suppose, I want to delete an index from my database. There are basically two methods for dropping indexes from MongoDb. One is to delete an individual index and other is delete all indexes from database.

To drop a particular index, dropIndex() method is used, which takes key as parameter. Below is the syntax for the same:

Drop Indexes from MongoDB:

To drop all indexes from database, dropIndexes() method is used. That will drop all the indexes present on collection.

Lets try to run and delete the index that we just created on OrganicChemistry key field:Drop Indexes MongoDB

In output we got nIndexesWas , which indicates that how many indexes were present before execution of this command, where as ok, indicates that the command run was successful.

This is all about creating. Finding and dropping indexes from database.

Back to top

What is projection with respect to MongoDB, how sorting is performed in MongoDB, explain with example?

Whenever we try to find some data from MongoDb, find() method is being used. This method will return me the documents of collection on which this is invoked. Now I can have the where clause as well in my MongoDb query so I can limit the output. Consider a scenerio where I want to retrieve particular fields of document, how to do so?

Lets dig more into it, for an example let say in our bookstore database, from ScienceBooks collection I want to find books with Author James. Whenever I will execute the find method MongoDb will return me the all the documents in the ScienceBooks collection in which Author is James. Now lets suppose I just want ISBN number of the books whose author is James. In order to achieve this there is a concept in MongoDb that is used and called Projection. Below is the syntax for the same:

In the command above, KeyName will be key whose corresponding fields we need to display. Flag to display takes 1 or 0 as input. 1 indicates that the corrospoinding values will be displayed where as 0 indicates that the corresponding values will not been displayed.

Lets try to simulate the same with example:MongoDB Projection TutorialAs we can see, the output of find command displayed all records of ScienceBooks collection. Now I want to have projection in place and want to see only name and not _id. Lets see how we can achieve this:MongoDB Projection Interview Questions

As we can see in the output, only name is in the output and not _id. And why it is, because if you see the find method, we have used display parameter ‘1’ with name and ‘0’ with _id.

This way we can use projection in our code to find the results which we want.

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

So far, we have covered beginners to intermediate level MongoDB Interview Questions in this Series. Next part in this series will contain more advanced MongoDB FAQs/Interview Questions with detailed examples and source code. Keep in touch :)

Top Technical Interview Questions and Answers Series:

ASP.NET Web API Expense Managment App with AngularJS

Goal of this ASP.NET Web API Tutorial is to develop a simple Expense Management Application that is mainly used to have a track of the expenses that an individual spend on a daily basis. Purpose is more to learn the technology and see the actual code snippets by keeping the application domain simple and straight forward. Technology being used for developing this Expense Management Application is AngularJS 1.x with ASP.NET Web API. The key features are:

  • Creating a user-defined Category.
  • Creating a expense for a corresponding Category with respect to date.
  • See Monthly Report of the expenses.

More ASP.NET Web API | AngularJs and Related Tutorial:

Setting Up ASP.NET Web API  Project:

  1. Create a New Project in Visual Studio 2013 or 2015.Visual Studio 2015 Application
  2. Create Blank Solutions in Other Project Types under Visual Studio Solutions.Microsoft Visual Studio 2015 Solution
  3. Add a project into the solution by Right clicking on Solution Name and select Add New Project. Select template as WEB API also ensure that no authentication is selected.ASP.NET Web API Tutorial
  4. Add another project for the angular application by repeating the same process, selecting Empty as template.Angularjs Tutorial App
  5. Add a new folder with name app to have the angular application markup and script files.
  6. Solution is set ready to work on our ExpenseManagement application.

Front End AngularJs Application:

  1. Right Click the app folder and create HTML pages and name them as:
    • Index.html
    • Category.html
    • Expense.html
    • Report.html
  2. Replace the following code in the index.html.

  3. Replace the following code in the register.html.

  4. Replace the following code in the login.html.

  5. Replace the following code in the category.html.

  6. Replace the following code in the expense.html

  7. Replace the following code in the report.html

Now the front end is ready which will look like:AngularJS Expense Web API

Expense Summary Web API Tutorial

Categories ASP.NET Web API

Report Web API Tutorial

Learn professional web development in AngularJS while building ten unique web apps

Following are the section details of this online course:

  • Section 1: Introduction
  • Section 2: Basic Angular Website
  • Section 3: Web Template Store
  • Section 4: myContacts App
  • Section 5: ngSocial Facebook App
  • Section 6: Job Directory
  • Section 7: KnowledgeBase
  • Section 8: User Authentication App
  • Section 9: Instagram Gallery
  • Section 10: PubNub Chat
  • Section 11: AutoFind
  • Section 12: Summary


Back End ASP.NET Web API 2.0 using Entity Framework 6.0:

Installation of Entity Framework

  1. Right click project in the solution explorer and select manage nugget packages for the project.
  2. NuGet package manager Dialog box appears as below.
  3. Search for Entity Framework.Entity Framework Tutorial
  4. Click on install
  5. Click I Accept License in License Agreement Pop up.

Generation of Model Classes using Entity Framework Database First Approach:

  1. Right click on the Model folder and project Add New Item.
  2. In the Add New Item Dialog box click on ADO.NET Entity Model(admx).EF Database First Approach
  3. Enter the name as ExpenseManagementDataModel.
  4. In the Select Tables/Views Dialog box by default select All radio button is selected.Entity Data Model Wizard
    Click Next and Click Finish.
  5. The admx Data Model is generated as below.Expense EDMX
  6. The solution explorer will contain the models and their configuration and context classes as below:Model in ASP.NET Web API

Creation of Web API Controllers Using the Scaffolding Technique:

  1. Right click controller folder and select Add -> New Scaffolded item.New Scaffolded Item
  2. Select the controller type as:Web API 2 Controller
  3. In the Add Controller window, select give Controller name, select the Model name which was created in the previous step using the drop down.Add Web API Controller
  4. By using the above step, select the Context class using the dropdown.

Implementing the Functionality using AngularJs:

Add the following code into the respective js pages which was created in step 3

App.js

categoryCtrl.js

ExpensesCtrl.js

loginCtrl.js

registerCtrl.js

reportCtrl.js

This ASP.NET Web API Tutorial covered many important areas related to AngularJS 1.x and Web API in a practical manner. User will also be able to download ASP.NET Web API Tutorial PDF later. Hopefully, as an ASP.NET Web Developer, one can take the code and improve the functionality as per his/her requirements and improve his/her skill as well.

Build your RESTful Web Service with ASP.NET Web API 2 from the ground up and learn how to use the new Attribute Routing. Click Here to Take the Video Course Now.
Course Contents are:

  • Build RESTful web services with Web API 2
  • Create custom URIs with Attribute Routing
  • Save data persistently in a database with Entity Framework Code First migrations
  • Use Attribute Routing to your advantage
  • Services and Dependency Injection
  • Use JQuery to create, read, update and delete objects with Web API 2

ASP.NET Web API 2

Advanced Web Developer Interview Questions Series:

Must Have NodeJS Interview Questions – Part 2

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.
process.channel 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”.
process.pid 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:

Must Have Node.Js Interview Questions

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:

Java Spring MVC Interview Questions – Part2

This Technical Interview Questions post is part2 of Java Spring MVC Interview Questions that will extend the initial FAQs list and add more Interview Questions on Spring MVC Framework. If you haven’t gone through the previous list of Spring MVC Interview Questions, I’ll strongly recommend to go through it.

Also, we have covered another comprehensive list of Interview Questions related to Microsoft ASP.NET MVC that you can follow here.

You can find latest Java Developer Jobs at the end of this Java Spring MVC tutorial.

Java Spring MVC Interview Questions List

What is bean wiring and @AutoWired annotation? Explain different modes of auto wiring? What are the limitations with Auto wiring?

Bean wiring, as names suggests, is wire a bean with a bean. Sounds a bit complex, lets put it in simple words. Lets go back to Dependency Injection, IoC container, where in to set property in a bean there are two ways, one is using Constructor , that is use <constructor-arg> and other one is use setter method, that is to use <property> tag. So using both these ways we can inject some to a bean, that can be some primitive, some properties or they can be another bean as well. When we inject a bean within a bean it is called wiring of beans.

Now come to Autowiring, what is autowiring? We can wire bean automatically using autowiring feature of spring and this autowiring can be done by two ways:

  • By Xml tags
  • By Annotations

Autowiring By Xml Tags:

In order to achieve auto wiring using xml tags, we just need add the autowire attribute in <bean> bean tag. For example:

And that’s all we need to do to autowire a bean. We will dig a more into an example, but before that lets talk about the types of autowiring supported by Spring:

There are 5 modes of autowiring supported:

  • Default or no : Default or no mode in autowiring suggests, that there is no autowiring and beans will be wired using ‘ref’. That mean we need to explicitly wire the bean.  When we write default or no as autowire mode, no autowiring will be done by spring container. Example is:
  • ByName : In this autowiring mode the autowiring is performed on the name of property.  If the name of bean is same as, name of a property of a bean, that is ofcourse different, then the bean will be autowired. The ByName of autowiring is applied to setter methods. In the example below DI will same as AutowireTutorial property and there will be a setter method in AutowireTutorialClass named setDI(DI di), with which the bean will be autowired. Lets look at the bean tag:
  • ByType : In this autowiring mode, autowiring is performed on the type of property. That means the container looks for the type of the property in the config file. Containter will go through the config file and looks for the same class type of bean and if found will autowire it. As the case with ByName, this property is also applicable to setter methods. In the example below DI will same as type in AutowireTutorial bean  and there will be a setter method in AutowireTutorialClass named setDI(DI di), with which the bean will be autowired. Lets look at the bean tag:
  • Constructor: It is same as ByType  autowiring mode with the only difference, that is mode is applicable to constructor instead of setter methods. Unlike above example of ByType , there will be a constructor as public AutowireTutorial(DI di){//} .
  • Autodetect : The autodetect wiring mode, as the name suggests  autowires with one of either constructor or ByType. When constructor mode is not able to detect dependencies then ByType mode is selected and beans are autowired accordingly.

This is all about the autowiring using xml tags. Now Lets come to another important aspect of autowiring that is autowiring using annotation.

Autowiring using Annotation:

As we discussed in above section how autowiring can be done using xml and bean tag. Now lets come to more powerful way to achieve autowiring that is using annotation. Spring provides @Autowired annotation, with help of this, autowiring can be achieved. The best part is that the annotation needs to directly placed over the property in class we need to autowire and rest all will be done by container, interesting isn’t it. The @Autowired  annotation can applied on Construtor, Setter methods, Properties etc. There is one attribute that is required once set to true, container will complain and throw exception in case when the dependency is not getting resolved. Lets look at an example.

Lets say we have a CellPhone class and it has some properties like brand, color, type. Lets suppose Type is a bean that we need to autowire with the CellPhone class using @Autowired annotation. Below are the steps how we will achieve this:

Type class:

CellPhone class will now have the autowired annotation on setter method, lets see how to write the same:

As we can see the setType method has the @Autowired annotation, which will make the Type bean to wire with CellPhone bean.

Now quickly look at the bean config file and see how it will look like: