Factory Method Pattern

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern

  • Factory Method Pattern allows the sub-classes to choose the type of objects to create.
  • It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.

Usage of Factory Design Pattern

  • When a class doesn’t know what sub-classes will be required to create
  • When a class wants that its sub-classes specify the objects to be created.
  • When the parent classes choose the creation of objects to its sub-classes.

UML for Factory Method Pattern

  • We are going to create a Plan abstract class and concrete classes that extends the Plan abstract class. A factory class GetPlanFactory is defined as a next step.
  • GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to GetPalnFactory to get the type of object it needs.


Abstract factory

Abstract Factory Pattern

Abstract Factory Pattern says that just define an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes.That means Abstract Factory lets a class returns a factory of classes. So, this is the reason that Abstract Factory Pattern is one level higher than the Factory Pattern.

An Abstract Factory Pattern is also known as Kit.

Advantage of Abstract Factory Pattern

  • Abstract Factory Pattern isolates the client code from concrete (implementation) classes.
  • It eases the exchanging of object families.
  • It promotes consistency among objects.

Usage of Abstract Factory Pattern

  • When the system needs to be independent of how its object are created, composed, and represented.
  • When the family of related objects has to be used together, then this constraint needs to be enforced.
  • When you want to provide a library of objects that does not show implementations and only reveals interfaces.
  • When the system needs to be configured with one of a multiple family of objects.

UML for Abstract Factory Pattern

  • We are going to create a Bank interface and a Loan abstract class as well as their sub-classes.
  • Then we will create AbstractFactory class as next step.
  • Then after we will create concrete classes, BankFactory, and LoanFactory that will extends AbstractFactory class
  • After that, AbstractFactoryPatternExample class uses the FactoryCreator to get an object of AbstractFactory class.
  • See the diagram carefully which is given below:



join two collections in mongodb using node js

Hi Friend Like Earlier Post today i would like to share my experience, Can we use Join in mongo DB like Sql?  Can We Use Where condition in mongo DB on Populated column?

Answer is YES. We can Use Join In Mongo DB and We can Use Condition on populated columns.

we can perform a left outer join by using the $lookup. The $lookup lets you specify which collection you want to join with the current collection, and which fields that should match. To apply condition on populated column use $unwind because look up return array and to access key need to use $unwind

Consider you have a “enquiries” collection and a “products” collection.
Enquiries collection have referance column for product.

Question is “want to accees Enquiry Data who enquire for product cotton shirt”

enquiries collection

“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “1”
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “2”
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “1”

products collection

“_id”: “1”,
“product_name”: “cotton shirt”
“_id”: “2”,
“product_name”: “cotton jeans”

Querry is:

{“$lookup”:{“from”:”products”,”localField”:”productid”,”foreignField”:”_id” ,”as” :”prod”}},
{“$match”:{ “prod.product_name” : “cotton shirt”}},


angular 8 new feature

What are New Features in angular 8?

Angular 8 have introduced some new feature and bug fixes.

Differential loading with modern browser

With new feature of angular 8 your apps will now be automagically more performant, when we create app build, two bundles will be created

  • Bundle for modern browsers that support ES2015+
  • Bundle for older browsers that only support the ES5 version of JavaScript.

The correct bundle will be loaded automatically by the browser.
This new feature results in the largest single performance improvement for Angular v8. Newer browsers will be able to load less code and load a much smaller amount of polyfills.

You don’t have to do anything special to benefit from differential loading, the ng build command with the –prod flag will take care of bundling everything

Dynamic imports for lazy routes

Get rid from typo error while lazy loading module. Now use the standard dynamic import syntax.

Old Syntax to add module in lazy load

{ path: ‘/customer’, loadChildren: ‘./customer/customer.module#CustomerModule’ }


Similar New Syntax will be

{ path: `/customer`, loadChildren: () => import(`./customer/customer.module`).then(m => m.CustomerModule) }


Ivy and Bazel New view rendering engine

New angular view engine Ivy and Bazel introduce in angular 8.

Bug Fixes

  • bazel: allow ts_library interop with list-typed inputs (#30600) (bf38df4)
  • bazel: Disable sandbox on Mac OS (#30460) (3de26a8)
  • bazel: ng test should run specific ts_web_test_suite (#30526) (8bc4da8)
  • core: remove deprecated TestBed.deprecatedOverrideProvider API (#30576) (5a46f94)
  • core: require ‘static’ flag on queries in typings (#30641) (c8af830)
  • core: temporarily remove @deprecated jsdoc tag for a TextBed.get overload (#30514) (561e01d), closes #29290#29905
  • router: type cast correctly for IE 11 bug breaking URL Unification when comparing objects (#30464) (32daa93)



what are generic way to handle error in node js

what are generic way to handle error in nodejs?

If you want to implement good app your applications must have informative error messages to notify clients exactly why their request has failed. Errors might be caused either by the client (e.g., wrong input data) or by the server (e.g., a bug in the code). what are resolution’s of error. for a best practice API error response must have following things

  • Error Code
  •  Message
  • Description
  • Resolution

For example:

“error”: {

       “code”: 10001,

       “message”: “Invalid Email”,

       “description”: “please enter valid email id.”,

       “resolution”: “your email must have or domain name”


Error Handling

Because of the asynchronous nature of Node.js and callback patterns, it’s not a trivial task to catch and log for future analysis the state in which errors happen. In the Chapter 17 of Pro Express.js, we cover the use of domains with Express.js apps. The use of domains for error handling in Express.js is a more advanced technique and, for most implementations right out of the box, framework’s built-in error handling might prove sufficient (along with custom error handling middleware).

The error handler spits out the error status (500, Internal Server Error), stack trace, and error message. It is enabled by this code only when the app is in development mode:

if (app.get(‘env’) === ‘development’) {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error’, {
message: err.message,
error: err


Tip: app.get(‘env’) is a convenient method for process.env.NODE_ENV; in other words, the preceding line can be rewritten with process.env.NODE_ENV === ‘development’

This makes sense because error handling is typically used across the whole application. Therefore, it’s best to implement it as middleware.

For custom error-handler implementations, the middleware is the same as any other except that it has one more parameter, error

// Main middleware
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display

We can use res.status(500).end() to achieve a similar result, because we’re not sending any data (e.g., an error message). It’s recommended to send at least a brief error message, because it will help the debugging process when problems occur. In fact, the response can be anything: JSON, text, a redirect to a static page, or something else.

app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
res.status(500).send({status:500, message: ‘internal error’, type:’internal’});

Note: as good practice Always using proper HTTP response statuses such as
401, 400, 500, and so on, is recommended. Refer to List 9–1 for a quick reference.

Main HTTP Status Codes

  • 200- OK; Standard response for successful HTTP requests
  • 201- Created; Request has been fulfilled. New resource created
  • 204- No Content; Request processed. No content returned
  • 301- Moved Permanently; This and all future requests directed to the given URI
  • 304- Not Modified; Resource has not been modified since last requested
  • 400- Bad Request; Request cannot be fulfilled due to bad syntax
  • 401- Unauthorized; Authentication is possible, but has failed
  • 403- Forbidden; Server refuses to respond to request
  • 404- Not Found; Requested resource could not be found
  • 500- Internal Server Error; Generic error message when server fails
  • 501- Not Implemented; Server does not recognize method or lacks ability to fulfill
  • 503- Service Unavailable; Server is currently unavailable



memento pattern


The word ‘memento’ refers to an object kept as a reminder or souvenir of a person or event. Memento pattern is a behavioral pattern in GoF because it captures and externalize an object’s internal state so that the object can be restored to this state at a later time.

source: GoF


Memento, the class that represents a snapshot, simply contains the state of an object to be restored to an Originator. You and get and set state that a Memento encapsulates inside.

Originator, the class in which the current state is held. Originator has a member function that creates and return a Memento with the current state of the Originator stored into the Memento. Originator also has a member function that sets its current state with the state of a given Memento object. In other words, it can create snapshot (Memento), or restore the state to the given snapshot (Memento).

Caretaker object keeps and holds the Mementos, but never modify the Mementos. Caretaker class is responsible for the memento’s safekeeping. Usually, Caretaker encapsulates a list of Mementos that you can add more to the list, or get a Memento from the list.


Memento class:

public class Memento {
private String state;

public Memento(String state){
this.state = state;

public String getState(){
return state;

Originator class:

public class Originator {
private String state;

public void setState(String state){
this.state = state;

public String getState(){
return state;

public Memento createMemento(){           // return a current snapshot
return new Memento(state);

public void setMemento(Memento Memento){  // restore from a snapshot
state = Memento.getState();

Caretaker class:

public class Caretaker {
private List<Memento> mementoList = new ArrayList<Memento>();

public void add(Memento state){

public Memento get(int index){
return mementoList.get(index);


public class MementoPatternDemo {
public static void main(String[] args) {

Originator originator = new Originator();
Caretaker caretaker = new Caretaker();

originator.setState(“State #1”);
originator.setState(“State #2”);

originator.setState(“State #3”);

originator.setState(“State #4”);
System.out.println(“Current State: ” + originator.getState());

System.out.println(“First saved State: ” + originator.getState());
System.out.println(“Second saved State: ” + originator.getState());


Current State: State #4
First saved State: State #2
Second saved State: State #3


  • Need an undo and restore mechanism.
  • Database rollback. To be able to rollback, have the Originator create a snapshot (memento) before performing an operation and thus in case of failure, the memento object would be used to restore the Originator to its previous state.
  • Want to simplify Originator code so it does not need to keep track of its previous state by moving such responsibility to the Caretaker code.


memento vs command

  • Both can act as magic tokens to be passed around and invoked at a later time.
  • ​In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time.
  • Both can support muti-level undos.
  • Memento pattern’s capturing and restoring object state is more expensive then Command patterns for Undo/Redo functionality.

singleton design pattern

Singleton design pattern


Sometimes it’s important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.


  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.


The implementation involves a static member in the “Singleton” class, a private constructor and a static public method that returns a reference to the static member.

Singleton Implementation - UML Class Diagram

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.

class Singleton
	private static Singleton instance;
	private Singleton()

	public static synchronized Singleton getInstance()
		if (instance == null)
			instance = new Singleton();

		return instance;
	public void doSomething()

You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.

The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner:


Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 – Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 – Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 – Accessing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let’s say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

Example 4 – Factories implemented as Singletons

Let’s assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multi threading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

Specific problems and implementation

Thread-safe implementation for multi-threading use.

A robust singleton implementation should work in any conditions. This is why we need to ensure it works when multiple threads uses it. As seen in the previous examples singletons can be used specifically in multi-threaded application to make sure the reads/writes are synchronized.

Early instantiation using implementation with static field

In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don’t need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.

Singleton – A simple example (java)

//Early instantiation using implementation with static field.
class Singleton
	private static Singleton instance = new Singleton();

	private Singleton()
		System.out.println("Singleton(): Initializing Instance");

	public static Singleton getInstance()
		return instance;

	public void doSomething()
		System.out.println("doSomething(): Singleton does something!");

Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singeton. This techique has 2 drawbacks that makes singleton inheritance impractical:

  • First of all, if the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
  • Second of all, in order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().

Multiple singleton instances if classes loaded by different classloaders access a singleton.

If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2 different clasess in memory.

Abstract Factory and Factory Methods implemented as singletons.

There are certain situations when the a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.

Hot Spot:

  • Multithreading – A special care should be taken when singleton has to be used in a multithreading application.
  • Serialization – When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
  • Classloaders – If the Singleton class is loaded by 2 different class loaders we’ll have 2 different classes, one for each class loader.
  • Global Access Point represented by the class name – The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.

Software design pattern

What is Software design pattern?

in Software industry it’s myth what is Software design pattern? and how to know which one is suitable for what module. can we create my own design pattern? to overcome this myth i had go through few article and tried to collect at one place, so let’s start.

Myth 1:- For a good architecture all design patterns have to be implemented in a project.

Fact: – Patterns come out naturally and is completely on-demand.

“Time tested Solution for recurring architecture problems”.

But frankly this definition will not hold true as you start implementing and reading design pattern. At one moment of time you will see design pattern is all about good OOP ( Object oriented programming) principles.

So let me put my definition as per my understanding and experience. I can guarantee that when we start running through all design patterns this definition would be more clear.

“Time tested Solution for recurring OOP problems”.

Categories of software design pattern 

Design patterns were originally grouped into the categories: creational patterns, structural patterns, and behavioral patterns, and described using the concepts of delegation, aggregation, and consultation. For further background on object-oriented design, see coupling and cohesion, inheritance, interface, and polymorphism. Another classification has also introduced the notion of architectural design pattern that may be applied at the architecture level of the software such as the Model–View–Controller pattern.

Creational patterns

Creational patterns further categorized into subcategories:

Ensure a class has only one instance, and provide a global point of access to it.
When to use:
Singleton pattern should be used when we must ensure that only one instance of a class is created and when the instance must be available through all the code. A special care should be taken in multi-threading environments when multiple threads must access the same resources through the same singleton object.
Abstract factory
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

When to use:

  • A system should be configured with one of multiple families of products
  • A system should be independent of how its products are created, composed and represented
  • Products from the same family should be used all together, products from different families should not be used togheter and this constraint must be ensured.
  • Only the product interfaces are revealed, the implementations remains hidden to the clients.

Separate the construction of a complex object from its representation, allowing the same construction process to create various representations.

Factory method
Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses (dependency injection).

Lazy initialization

Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. This pattern appears in the GoF catalog as “virtual proxy”, an implementation strategy for the Proxy pattern.
When to use:
Basically, we’ll use an object pool whenever there are several clients who needs the same stateless resource which is expensive to create. like Database Connections, Remote Objects

Specify the kinds of objects to create using a prototypical instance, and create new objects from the ‘skeleton’ of an existing object, thus boosting performance and keeping memory footprints to a minimum.

Structural patterns

Structural patterns further categorized into subcategories:

Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator.

Decouple an abstraction from its implementation allowing the two to vary independently.

Provide a surrogate or placeholder for another object to control access to it.

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Use sharing to support large numbers of similar objects efficiently.

Behavioral Design Patterns

Behavioral Design Patterns further categorized into subcategories:

Chain of Responsibly
It avoids attaching the sender of a request to its receiver, giving this way other objects the possibility of handling the request too.
The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it.

Encapsulate a request in an object, Allows the parameterization of clients with different requests and Allows saving the requests in a queue.

Without violating encapsulation, capture and externalize an object’s internal state allowing the object to be restored to this state later.


Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language / Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses / Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm’s structure.

Represents an operation to be performed on the elements of an object structure / Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Null Object
Provide an object as a surrogate for the lack of an object of a given type. / The Null Object Pattern provides intelligent do nothing behavior, hiding the details from its collaborators.


What is MEAN Technology

So, what is a MEAN stack? The idea is quite simple actually – there are 4 main parts:

These are some of the advantages of a MEAN stack:

  • Single language is used in the whole application
  • Support for the MVC pattern
  • JSON is used for transfering data
  • Node.js’s huge module library
  • Open source so you can tweak it to your preferences if you’re an experienced user

OK, enough with the chit-chat, now we’ll go and install all the necessary parts.

How to Install and Configure MongoDB on Ubuntu

Import the public key used by the package management system.

The Ubuntu package management tools (i.e. dpkg and apt) ensure package consistency and authenticity by requiring that distributors sign packages with GPG keys. Issue the following command to import the MongoDB public GPG Key:

sudo apt-key adv --keyserver hkp:// --recv 0C49F3730359A14518585931BC711F9BA15703C6

2. Create a list file for MongoDB.

Create the /etc/apt/sources.list.d/mongodb-org-3.4.list list file using the command appropriate for your version of Ubuntu:

Ubuntu 12.04
echo "deb [ arch=amd64 ] precise/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
Ubuntu 14.04
echo "deb [ arch=amd64 ] trusty/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
Ubuntu 16.04
echo "deb [ arch=amd64,arm64 ] xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

3. Reload local package database.

Issue the following command to reload the local package database:

sudo apt-get update

4. Install the MongoDB packages.

Install the latest stable version of MongoDB.

Issue the following command:

sudo apt-get install -y mongodb-org

Run MongoDB Community Edition

Most Unix-like operating systems limit the system resources that a session may use. These limits may negatively impact MongoDB operation. See UNIX ulimit Settings for more information.

The MongoDB instance stores its data files in /var/lib/mongodb and its log files in /var/log/mongodbby default, and runs using the mongodb user account. You can specify alternate log and data file directories in /etc/mongod.conf. See systemLog.path and storage.dbPath for additional information.

If you change the user that runs the MongoDB process, you must modify the access control rights to the /var/lib/mongodb and /var/log/mongodb directories to give this user access to these directories.

1. Start MongoDB.

Issue the following command to start mongod:

sudo service mongod start

2. Verify that MongoDB has started successfully

Verify that the mongod process has started successfully by checking the contents of the log file at/var/log/mongodb/mongod.log for a line reading

[initandlisten] waiting for connections on port 

where is the port configured in /etc/mongod.conf, 27017 by default.

3. Stop MongoDB.

As needed, you can stop the mongod process by issuing the following command:

sudo service mongod stop

4. Restart MongoDB.

Issue the following command to restart mongod:

sudo service mongod restart

5. Begin using MongoDB.

To help you start using MongoDB, MongoDB provides Getting Started Guides in various driver editions. See Getting Started for the available editions.

Before deploying MongoDB in a production environment, consider the Production Notes document.

Later, to stop MongoDB, press Control+C in the terminal where the mongod instance is running.

Native Mongodb management tool or admin UI

Robomongo is a shell-centric cross-platform MongoDB management tool. Unlike most other MongoDB admin UI tools, Robomongo embeds the actual mongo shell in a tabbed interface with access to a shell command line as well as GUI interaction.

How to Install Robomongo

Click here to download robomongo tool. here is steps for connecting to mongo db

To add your DocumentDB: API for MongoDB account to the Robomongo MongoDB Connections, perform the following steps.

  1. Retrieve your DocumentDB: API for MongoDB account connection information using the instructions here.Screen shot of the connection string blade
  2. Run Robomongo.exe
  3. Click the connection button under File to manage your connections. Then, click Create in the MongoDB Connections window, which will open up the Connection Settings window.
  4. In the Connection Settings window, choose a name. Then, find the Host and Port from your connection information in Step 1 and enter them into Address and Port, respectively.Screen shot of the Robomongo Manage Connections
  5. On the Authentication tab, click Perform authentication. Then, enter your Database (default is Admin), User Name and Password. Both User Name and Password can be found in your connection information in Step 1.Screen shot of the Robomongo Authentication Tab
  6. On the SSL tab, check Use SSL protocol, then change the Authentication Method to Self-signed Certificate.Screen shot of the Robomongo SSL Tab
  7. Finally, click Test to verify that you are able to connect, then Save.

How to Install Express

Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory.

$ mkdir myapp
$ cd myapp
Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.

$ npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

entry point: (index.js)
Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.

Now install Express in the myapp directory and save it in the dependencies list. For example:

$ npm install express –save
To install Express temporarily and not add it to the dependencies list, omit the –save option:

$ npm install express
Node modules installed with the –save option are added to the dependencies list in the package.json file. Afterwards, running npm install in the app directory will automatically install modules in the dependencies list.

How to Install Nodejs

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Latest version node.js ppa is maintaining by its official website. We can add this PPA to Ubuntu 16.04 LTS (Trusty Tahr) and 14.04 LTS (Xenial Xerus) Systems and install node.js with few easy commands.

Step 1: Add NodeJs PPA

First, you need to node.js PPA in our system provides by nodejs official website. We also need to install python-software-properties package if not installed already.

$ sudo apt-get install python-software-properties
$ curl -sL | sudo -E bash –
Step 2: Install Node.js and NPM

After adding required PPA file lets install Node package. NPM will also be installed with node.js. This command will also install many other dependent packages on your system.

$ sudo apt-get install nodejs
Step 3: Check Node.js and NPM Version

After installing node.js verify and check the installed version. You can find more details about current version on node.js official website.

$ node -v

Also, check the version of installed npm.

$ npm -v

Step 4: Create Demo Web Server (Optional)

This is an optional step. If you want to test your node.js install. Let’s create a web server with “Hello World!” text. Create a file http_server.js

$ vim http_server.js
and add following content

var http = require(‘http’);
http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
res.end(‘Hello World\n’);
}).listen(3001, “”);
console.log(‘Server running at’);
Now start the web server using below command.

$ node –debug http_server.js

debugger listening on port 5858
Server running at
The web server has been started on port 3001. Now access URL in browser. Now you will need to configure a front end server for your app.