Home Web Development MEAN Web Development - Second Edition

MEAN Web Development - Second Edition

By Amos Q. Haviv
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to MEAN
About this book
The MEAN stack is a collection of the most popular modern tools for web development that helps you build fast, robust, and maintainable web applications. Starting with the MEAN core frameworks, this pragmatic guide will explain the key concepts of each framework, how to set them up properly, and how to use popular modules to connect it all together. By following the real-world examples shown in this tutorial, you will scaffold your MEAN application architecture, add an authentication layer, and develop an MVC structure to support your project development. You will learn the best practices of maintaining clear and simple code and will see how to avoid common pitfalls. Finally, you will walk through the different tools and frameworks that will help expedite your daily development cycles. Watch how your application development grows by learning from the only guide that is solely orientated towards building a full, end-to-end, real-time application using the MEAN stack!
Publication date:
November 2016
Publisher
Packt
Pages
368
ISBN
9781785886300

 

Chapter 1. Introduction to MEAN

The MEAN stack is a powerful, full-stack JavaScript solution that comprises four major building blocks: MongoDB as the database, Express as the web server framework, Angular as the web client framework, and Node.js as the server platform. These building blocks are being developed by different teams, and involve a substantial community of developers and advocates pushing forward the development and documentation of each component. The main strength of the stack lies in its centralization of JavaScript as the main programming language. However, the problem of connecting these tools together can lay the foundation for scaling and architecture issues, which can dramatically affect your development process.

In this book, I will try to present the best practices and known issues of building a MEAN application, but before you begin with actual MEAN development, you will first need to set up your environment. This chapter will cover a bit of a programming overview, but mostly present the proper ways of installing the basic perquisites of a MEAN application. By the end of this chapter, you'll learn how to install and configure MongoDB and Node.js on all the common operating systems and how to use NPM. In this chapter, we will cover the following topics:

  • Introduction to the MEAN stack architecture

  • Installing and running MongoDB on Windows, Linux, and Mac OS X

  • Installing and running Node.js on Windows, Linux, and Mac OS X

  • Introduction to npm and how to use it to install Node modules

 

Three-tier web application development


Most web applications are built in a three-tier architecture that consists of three important layers: data, logic, and presentation. In web applications, the application structure usually breaks down to database, server, and client, while in modern web development, it can also be broken into database, server logic, client logic, and client UI.

A popular paradigm for implementing this model is the Model-View-Controller (MVC) architectural pattern. In the MVC paradigm, the logic, data, and visualization are separated into three types of object, each handling its own tasks. The View handles the visual part, taking care of user interaction. The Controller responds to system and user events, commanding the Model and View to change appropriately. The Model handles data manipulation, responding to requests for information or changing its state according to the Controller's instructions. A simple visual representation of the MVC architecture is shown in the following diagram:

Common MVC architecture communication

In the 25 years of web development, many technology stacks became popular for building three-tier web applications. Among those now ubiquitous stacks, you can find the LAMP stack, the .NET stack, and a rich variety of other frameworks and tools. The main problem with these stacks is that each tier demands a knowledge base that usually exceeds the abilities of a single developer, making teams bigger than they should be, less productive, and exposed to unexpected risks.

 

The evolution of JavaScript


JavaScript is an interpreted computer programming language that was built for the Web. First implemented by the Netscape Navigator web browser, it became the programming language that web browsers use to execute client-side logic. In the mid 2000s, the shift from websites to web applications, along with the release of faster browsers, gradually created a community of JavaScript developers writing more complex applications. These developers started creating libraries and tools that shortened development cycles, giving birth to a new generation of even more advanced web applications. They, in turn, created a continuous demand for better browsers. This cycle went on for a few years, where the vendors kept improving their browsers and JavaScript developers kept pushing the boundaries.

The real revolution began in 2008, when Google released its Chrome browser, along with its fast JIT-compiling V8 JavaScript engine. Google's V8 engine made JavaScript run so much faster that it completely transformed web application development. More importantly, the release of the engine's source code allowed developers to start reimagining JavaScript outside of the browser. One of the first products of this revolution was Node.js.

After looking into other options for a while, programmer Ryan Dahl found that V8 engine fit his non-blocking I/O experiment called Node.js. The idea was simple: help developers build non-blocking units of code to allow better use of system resources and create more responsive applications. The result was a minimal yet powerful platform, which utilized JavaScript's non-blocking nature outside of the browser. Node's elegant module system enabled developers to freely extend the platform using third-party modules to achieve almost any functionality. The reaction by the online community was a creation of various tools, from modern web frameworks to robotics server platforms. However, server-side JavaScript was only the beginning.

When Dwight Merriman and Eliot Horowitz set out to build their scalable hosting solution back in 2007, they already had a lot of experience with building web applications. However, the platform they built did not succeed as planned, so in 2009, they decided to take it apart and open source its components, including a V8-based database called MongoDB. Derived from the word "humongous", MongoDB was a scalable NoSQL database that used a JSON-like data model with dynamic schemas. MongoDB gained a lot of traction right away by giving developers the flexibility they needed when dealing with complex data, while providing RDBMS features such as advanced queries and easy scaling—features that eventually made MongoDB one of the leading NoSQL solutions. JavaScript broke another boundary. However, the JavaScript revolutionaries haven't forgotten where it all began. In fact, the popularization of modern browsers created a new wave of JavaScript frontend frameworks.

Back in 2009, while building their JSON as a platform service, developers Miško Hevery and Adam Abrons noticed that the common JavaScript libraries weren't enough. The nature of their rich web application raised the need for a more structured framework that would reduce grunt work and maintain an organized code base. Abandoning the original idea, they decided to focus on the development of their frontend framework and open sourced the project, naming it AngularJS. The idea was to bridge the gap between JavaScript and HTML, and help popularize single-page application development.

The result was a rich web framework, which presented frontend web developers with concepts such as two-way data binding, cross-component dependency injection, and MVC-based components. Angular, along with other modern frameworks, revolutionized web development by transforming the once unmaintainable frontend code base into a structured code base that can support more advanced development paradigms such as Test-driven Development (TDD).

The rise of open source collaboration tools, along with the devoted involvement of these talented engineers, created one of the richest communities in the world. More importantly, these major advancements allowed the development of three-tier web applications to be unified under JavaScript as the programming language across all three layers—an idea that is commonly referred to as the full-stack JavaScript. The MEAN stack is just a single example of this idea.

 

Introduction to ECMAScript 2015


After years of work, the ES6 specification was released on June 2015. It presented the biggest advancements in JavaScript since ES5 and introduced several features into the language that will completely transform the way we JavaScript developers write code. It would be ambitious to describe all the improvements made by ES2015. Instead, let's try to work through the basic features we'll use in the next chapters.

Modules

Modules are now a supported language-level feature. They allow developers to wrap their component in a Module pattern, and export and import modules inside their code. The implementation is very similar to the CommonJS module implementation described in the previous chapters, although ES2015 modules also support asynchronous loading. The basic keywords for working with ES2015 modules are export and import. Let's look at a simple example. Suppose you have a file named lib.js that contains the following code:

export function halfOf(x) {
    return x / 2;
}

So, in your main.js file, you can use the following code:

import halfOf from 'lib';
console.log(halfOf(84));

However, modules can be much more fun. For instance, let's say our lib.js file looks like this:

export function halfOf(x) {
    return x / 2;
}
export function multiply(x, y) {
    return x * y;
}

In your main file, use the following code:

import {halfOf, multiply} from 'lib';
console.log(halfOf(84));
console.log(multiply(21, 2));

ES2015 modules also support default export values. So, for instance, let's say you have file named doSomething.js that contains the following code:

export default function () { 
    console.log('I did something')
};

You'll be able to use it as follows in your main.js file:

import doSomething from 'doSomething';
doSomething();

It is important to remember that the default import should identify their entities using the module name.

Another important thing to remember is that modules export bindings and not values. So for instance, let's say you have a validator.js file that looks like this:

export let flag = false;
export function touch() {
    flag = true;
}

You also have a main.js file that looks like this:

import { flag, touch } from 'validator';
console.log(flag); 
touch();
console.log(flag); 

The first output would be false, and the second would be true. Now that we have a basic understanding of modules, let's move to classes.

Classes

The long debate about classes versus prototypes came to a conclusion that classes in ES2015 are basically just a syntactic sugar over the prototype-based inheritance. Classes are easy-to-use patterns that support instance and static members, constructors, and super calls. Here is an example:

class Vehicle {
    constructor(wheels) {
        this.wheels = wheels;
    }
    toString() {
        return '(' + this.wheels + ')';
    }
}

class Car extends Vehicle {
    constructor(color) {
        super(4);
        this.color = color;
    }
    toString() {
        return super.toString() + ' colored:  ' + this.color;
    }
}

let car = new Car('blue');
car.toString(); 

console.log(car instanceof Car); 
console.log(car instanceof Vehicle); 

In this example, the Car class extends the Vehicle class. Thus, the output is as follows:

 (4) in blue
true
true

Arrow functions

Arrows are functions shorthand by the => syntax. For people familiar with other languages such as C# and Java 8, they might look familiar. However, arrows are also very helpful because they share the same lexical this as their scope. They are mainly used in two forms. One is using an expression body:

const squares = numbers.map(n => n * n); 

Another form is using a statement body:

numbers.forEach(n => {
  if (n % 2 === 0) evens.push(n);
});

An example of using the shared lexical would be:

const author = {
  fullName: "Bob Alice",
  books: [],
  printBooks() {
     this.books.forEach(book => console.log(book + ' by ' + this.fullName));
  }
};

If used as a regular function, this would be the book object and not the author.

Let and Const

Let and Const are new keywords used for symbol declaration. Let is almost identical to the var keyword, so it'll behave the same as global and function variables. However, let behaves differently inside a block. For instance, look at the following code:

function iterateVar() {
  for(var i = 0; i < 10; i++) {
    console.log(i);
  }

  console.log(i)
}

function iterateLet() {
  for(let i = 0; i < 10; i++) {
    console.log(i);
  }
  
  console.log(i)
}

The first function will print i after the loop, but the second one will throw an error, since i is defined by let.

The const keyword forces single assignment. So, this code will throw an error as well:

const me = 1
me = 2

Default, Rest, and Spread

Default, Rest, and Spread are three new features related to functions parameters. The default feature allows you to set a default value to the function parameter:

function add(x, y = 0) {
    return x + y;
}
add(1) 
add(1,2)

In this example, the value of y will be set to 0 if a value is not passed or is set to undefined.

The Rest feature allows you to pass an array as trailing arguments as follows:

function userFriends(user, ...friends) {
  console.log(user + ' has ' + friends.length + ' friends');
}
userFriends('User', 'Bob', 'Alice');

The Spread feature turns an array into a call argument:

function userTopFriends(firstFriend, secondFriend, thirdFriends) {
  console.log(firstFriend);
  console.log(secondFriend);
  console.log(thirdFriends);
}

userTopFriends(...['Alice', 'Bob', 'Michelle']);

Summary

Going into modern web development, ES2015 will become a viable part of your daily programming sessions. What is shown here is the tip of the iceberg, and it is strongly recommended that you continue to investigate it deeper. However, for the purposes of this book, it will suffice.

 

Introducing MEAN


MEAN is an abbreviation for MongoDB, Express, Angular, and Node.js. The concept behind it is to use only JavaScript-driven solutions to cover the different parts of your application. The advantages are great and are as follows:

  • A single language is used throughout the application

  • All the parts of the application can support and often enforce the use of the MVC architecture

  • Serialization and deserialization of data structures is no longer needed, because data marshaling is done using JSON objects

However, there are still a few important questions that remain unanswered:

  • How do you connect all the components together?

  • Node.js has a huge ecosystem of modules, so which modules should you use?

  • JavaScript is paradigm agnostic, so how can you maintain the MVC application structure?

  • JSON is a schema-less data structure, so how and when should you model your data?

  • How do you handle user authentication?

  • How should you use the Node.js non-blocking architecture to support real-time interactions?

  • How can you test your MEAN application code base?

  • Considering the rise of DevOps and CI, what kind of JavaScript development tools can you use to expedite your MEAN application development process?

In this book, I'll try to answer these questions and many more. However, before we go any further, you will first need to install the basic prerequisites.

 

Installing MongoDB


For MongoDB's stable versions, the official MongoDB website supplies linked binaries that provide the easiest way to install MongoDB on Linux, Mac OS X, and Windows. Notice that you need to download the right architecture version for your operating system. If you use Windows or Linux, ensure that you download either the 32-bit or 64-bit version according to your system architecture. Mac users are safe to download the 64-bit version.

Note

The MongoDB versioning scheme works in such a way that only even version numbers mark stable releases. So, versions 3.0.x and 3.2x are stable, while 2.9.x and 3.1.x are unstable releases and should not be used in production. The latest stable version of MongoDB is 3.2.x.

When you visit the download page at http://mongodb.org/downloads, you'll be offered a download of an archive that contains the binaries you need to install MongoDB. After downloading and extracting the archive file, you will need to locate the mongod binary, which is usually located in the bin folder. The mongod process runs the main MongoDB server process, which can be used as a standalone server or a single node of a MongoDB replica set. In our case, we will use MongoDB as a standalone server. The mongod process requires a folder to store the database files (the default folder is /data/db) and a port to listen to (the default port is 27017). In the following subsections, we'll go over the setup steps for each operating system. We'll begin with the common Windows installation process.

Note

It is recommended that you learn more about MongoDB by visiting the official documentation at https://mongodb.org.

Installing MongoDB on Windows

Once you have downloaded the right version, run the .msi file. MongoDB should be installed in the C:\Program Files\MongoDB\ folder. While running, MongoDB uses a default folder to store its data files. On Windows, the default folder location is C:\data\db. So, in the command prompt, go to C:\ and issue the following command:

> md c:\data\db

Tip

You can tell the mongod service to use an alternative path for the data files, using the --dbpath command-line flag.

Once you've finished creating the data folders, you'll get two options while running the main MongoDB service.

Running MongoDB manually

To run MongoDB manually, you will need to run the mongod binary. So, open the command prompt and navigate to the C:\Program Files\MongoDB\Server\3.2\bin folder. Then, issue the following command:

C:\Program Files\MongoDB\Server\3.2\bin> mongod

The preceding command will run the main MongoDB service that starts listening to the default 27017 port. If everything goes well, you should see a console output similar to the following screenshot:

Running the MongoDB server on Windows

Depending on the Windows security level, a security alert dialog, which notifies you about the blocking of some service features, will be issued. If this occurs, select a private network and click on Allow Access.

Note

You should be aware that the MongoDB service is self-contained, so you can alternatively run it from any folder of your choice.

Running MongoDB as a Windows service

The more popular approach is running MongoDB automatically after every reboot cycle. Before you begin setting up MongoDB as a Windows service, it's considered a good practice to specify a path for the MongoDB log and configuration files. Start by creating a folder for these files by running the following command in your command prompt:

> md C:\data\log

Then, you'll need to create a configuration file at C:\Program Files\MongoDB\Server\3.2\mongod.cfg that contains these lines:

systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db

When you have your configuration file in place, open a new command prompt window with administrative privileges by right-clicking on the command prompt icon and clicking on Run as administrator. Notice that if an older version of the MongoDB service is already running, you'll first need to remove it using the following commands:

> sc stop MongoDB
> sc delete MongoDB

Then, install the MongoDB service by running the following command:

> "C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\3.2\mongod.cfg" --install

Notice that the install process will only succeed if your configuration file is set correctly. After installing your MongoDB service, you can run it by executing the following command in the administrative command prompt window:

> net start MongoDB

Be aware that the MongoDB configuration file can be modified to accommodate your needs. You can learn more about it by visiting http://docs.mongodb.org/manual/reference/configuration-options/.

Installing MongoDB on Mac OS X and Linux

In this section, you'll learn the different ways of installing MongoDB on Unix-based operating systems. Let's begin with the simplest way to install MongoDB, which involves downloading MongoDB's precompiled binaries.

Installing MongoDB from binaries

You can download the right version of MongoDB using the download page at http://www.mongodb.org/downloads. Alternatively, you can do this via CURL by executing the following command:

$ curl -O http://downloads.mongodb.org/osx/mongodb-osx-x86_64-3.2.10.tgz

Notice that we have downloaded the Mac OS X 64-bit version, so make sure you alter the command to fit the version suitable for your machine. After the downloading process is over, unpack the file by issuing the following command in your command-line tool:

$ tar -zxvf mongodb-osx-x86_64-3.2.10.tgz

Now, change the name of the extracted folder to a simpler folder name by running the following command:

$ mv mongodb-osx-x86_64-3.2.10 mongodb

MongoDB uses a default folder to store its files. On Linux and Mac OS X, the default location is /data/db, so in your command-line tool, run the following command:

$ mkdir -p /data/db

Tip

You may experience some trouble creating this folder. This is usually a permission issue, so use sudo or super user when running the preceding command.

The preceding command will create the data and db folders, because the –p flag creates parent folders as well. Notice that the default folder is located outside your home folder, so make sure you set the folder permission by running the following command:

$ chown -R $USER /data/db

Now that you have everything prepared, use your command-line tool and go to the bin folder to run the mongod service as follows:

$ cd mongodb/bin
$ mongod

This will run the main MongoDB service, which will start listening to the default 27017 port. If everything goes well, you should see a console output similar to the following screenshot:

Running the MongoDB server on Mac OS X

Installing MongoDB using a package manager

Sometimes, the easiest way to install MongoDB is using a package manager. The downside is that some package managers are falling behind in terms of supporting the latest version. Luckily, the team behind MongoDB also maintains the official packages for RedHat, Debian, and Ubuntu, as well as a Homebrew package for Mac OS X. Note that you'll have to configure your package manager repository to include the MongoDB servers to download the official packages.

To install MongoDB on Red Hat Enterprise, CentOS, or Fedora using Yum, follow the instructions at http://docs.mongodb.org/manual/tutorial/install-mongodb-on-red-hat-centos-or-fedora-linux/.

To install MongoDB on Ubuntu using APT, follow the instructions at http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/.

To install MongoDB on Debian using APT, follow the instructions at http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian/.

To install MongoDB on Mac OS X using Homebrew, follow the instructions at http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/.

Using the MongoDB shell

The MongoDB archive file includes the MongoDB shell, which allows to you to interact with your server instance using the command line. To start the shell, navigate to the MongoDB bin folder and run the mongo service as follows:

$ cd mongodb/bin
$ mongo

If you successfully installed MongoDB, the shell will automatically connect to your local instance, using the test database. You should see a console output similar to the following screenshot:

Running the MongoDB shell on Mac OS X

To test your database, run the following command:

> db.articles.insert({title: "Hello World"})

The preceding command will create a new article collection and insert a JSON object containing a title property. To retrieve the article object, execute the following command:

> db.articles.find()

The console will output a text similar to the following message:

{ _id: ObjectId("52d02240e4b01d67d71ad577"), title: "Hello World" }

Congratulations! This means your MongoDB instance is working properly, and you have successfully managed to interact with it using the MongoDB shell. In the upcoming chapters, you'll learn more about MongoDB and how to use the MongoDB shell.

 

Installing Node.js


For the stable versions, the official Node.js website supplies linked binaries that provide the easiest way to install Node.js on Linux, Mac OS X, and Windows. Note that you need to download the right architecture version for your operating system. If you use Windows or Linux, make sure to download either the 32-bit or 64-bit version according to your system architecture. Mac users are safe to download the 64-bit version.

Note

After the merge between the Node.js and io.js projects, the version scheme continued directly from 0.12.x to 4.x. The team now uses the Long-term Support (LTS) policy. You can read about it at https://en.wikipedia.org/wiki/Long-term_support. The latest stable version of Node.js is 6.x.

Installing Node.js on Windows

Installing Node.js on a Windows machine is a simple task that can be easily accomplished using the standalone installer. To begin with, navigate to https://nodejs.org/en/download/ and download the right .msi file. Notice there are 32-bit and 64-bit versions, so make sure you download the right one for your system.

After downloading the installer, run it. If you get any security dialog boxes, just click on the Run button, and the installation wizard should start. You will be prompted with an installation screen similar to the following screenshot:

Node.js Windows installation wizard

Once you click on the Next button, the installation should begin. A few moments later, you'll see a confirmation screen similar to the following screenshot, telling you that Node.js was successfully installed:

Node.js Windows installation confirmation

Installing Node.js on Mac OS X

Installing Node.js on Mac OS X is a simple task that can be easily accomplished using the standalone installer. Start by navigating to the https://nodejs.org/en/download/ page and download the .pkg file. After downloading the installer, run it, and you will be prompted with an installation screen similar to the following screenshot:

Node.js Mac OS X installation wizard

Click on Continue, and the installation process should begin. The installer will ask you to confirm the license agreement and then ask you to select the folder destination. Choose the option most suitable for you before clicking on the Continue button again. The installer will then ask you to confirm the installation information and ask you for your user password. A few moments later, you'll see a confirmation screen similar to the following screenshot, telling you that Node.js was successfully installed:

Node.js Mac OS X installation confirmation

Installing Node.js on Linux

To install Node.js on a Linux machine, you'll have to use the tarball file from the official website. The best way of doing so is to download the latest version and then build and install the source code using the make command. Start by navigating to the http://nodejs.org/en/download/ page, and download the suitable .tar.gz file. Then, expand the file and install Node.js by issuing the following commands:

$ tar -zxf node-v6.9.1.tar.gz
$ cd node-v6.9.1
$ ./configure && make && sudo make install

If everything goes well, the commands will install Node.js on your machine. Note that these commands are for the Node.js 6.9.1 version, so remember to replace the version number with the version you downloaded.

Note

It is recommended that you learn more about Node.js by visiting the official documentation at https://nodejs.org.

Running Node.js

After you have successfully installed Node.js, you will be able to start experimenting with it using the provided command-line interface (CLI). Go to your command-line tool and execute the following command:

$ node

This will start the Node.js CLI, which will wait for a JavaScript input. To test the installation, run the following command:

> console.log('Node is up and running!');

The output should be similar to the one that follows:

Node is up and running!
undefined

This is nice, but you should also try to execute a JavaScript file. Start by creating a file named application.js that contains the following code:

console.log('Node is up and running!');

To run it, you'll have to pass the file name as the first argument to the Node CLI by issuing the following command:

$ node application.js
Node is up and running!

Congratulations! You have just created your first Node.js application. To stop the CLI, press CTRL + D or CTRL + C.

 

Introducing npm


Node.js is a platform, which means its features and APIs are kept to a minimum. To achieve more complex functionality, it uses a module system that allows you to extend the platform. The best way to install, update, and remove Node.js modules is using npm. npm is mainly used as:

  • A registry of packages for browsing, downloading, and installing third-party modules

  • A CLI tool to manage local and global packages

Conveniently, npm is installed during the Node.js installation process, so let's quickly jump in and learn how to use it.

Using npm

To understand how npm works, we will install the Express web framework module, which you'll use in the upcoming chapters. npm is a robust package manager, which keeps a centralized registry for public modules. To browse the available public packages, visit the official website at https://www.npmjs.com/.

Most of the packages in the registry are open source and contributed by the Node.js community developers. When developing an open source module, the package author can decide to publish it to the central registry, allowing other developers to download and use it in their projects. In the package configuration file, the author will choose a name that will later be used as a unique identifier to download that package.

Note

It is recommended that you learn more about Node.js by visiting the official documentation at https://docs.npmjs.com.

The installation process of npm

It is important to remember that npm has two installation modes: local and global. The default local mode is used more often and installs third-party packages in a local node_modules folder placed inside your application folder. It has no effect system-wise and is used to install the packages your application needs, without polluting your system with unnecessary global files.

The global mode is used to install the packages you want Node.js to use globally. Usually, these are CLI tools, such as Grunt, that you'll learn about in the upcoming chapters. Most of the time, the package author will specifically instruct you to install the package globally. Therefore, whenever in doubt, use the local mode. The global mode will usually install the packages in the /usr/local/lib/node_modules folder for Unix-based systems and the C:\Users\%USERNAME%\AppData\Roaming\npm\node_modules folder for Windows-based systems, making it available to any Node.js application running on the system.

Installing a package using npm

Once you find the right package, you'll be able to install it using the npm install command, as follows:

$ npm install <Package Unique Name>

Installing a module globally is similar to its local counterpart, but you'll have to add the –g flag, as follows:

$ npm install –g <Package Unique Name>

Note

You may find out that your user doesn't have the right permissions to install packages globally, so you'll have to use the root user or install it using sudo.

For example, to locally install Express, you'll need to navigate to your application folder and issue the following command:

$ npm install express

The preceding command will install the latest stable version of the Express package in your local node_modules folder. Furthermore, npm supports a wide range of semantic versioning. So, to install a specific version of a package, you can use the npm install command, as follows:

$ npm install <Package Unique Name>@<Package Version>

For instance, to install the second major version of the Express package, you'll need to issue the following command:

$ npm install express@2.x 

This will install the latest stable version of Express 2. Note that this syntax enables npm to download and install any minor version of Express 2. To learn more about the supported semantic versioning syntax, it is recommended that you visit https://github.com/npm/node-semver.

When a package has dependencies, npm will automatically resolve those dependencies, installing the required packages in a node_modules folder inside the package folder. In the preceding example, the Express dependencies will be installed under node_modules/express/node_modules.

Removing a package using npm

To remove an installed package, you'll have to navigate to your application folder and run the following command:

$ npm uninstall < Package Unique Name>

npm will then look for the package and try to remove it from the local node_modules folder. To remove a global package, you'll need to use the -g flag, as follows:

$ npm uninstall –g < Package Unique Name>
Updating a package using npm

To update a package to its latest version, issue the following command:

$ npm update < Package Unique Name>

npm will download and install the latest version of this package, even if it doesn't exist yet. To update a global package, use the following command:

$ npm update –g < Package Unique Name>

Managing dependencies using the package.json file

Installing a single package is nice, but pretty soon, your application will need to use several packages. So, you'll need a better way to manage these dependencies. For this purpose, npm allows you to use a configuration file named package.json in the root folder of your application. In your package.json file, you'll be able to define various metadata properties of your application, including properties such as the name, version, and author of your application. This is also where you define your application dependencies.

The package.json file is basically a JSON file that contains the different attributes you'll need to describe your application properties. An application using the latest Express and Grunt packages will have a package.json file as follows:

{
  "name" : "MEAN",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "latest",
    "grunt" : "latest"
  }
}

Note

Your application name and version properties are required, so removing these properties will prevent npm from working properly.

Creating a package.json file

While you can manually create a package.json file, an easier approach would be to use the npm init command. To do so, use your command-line tool and issue the following command:

$ npm init

npm will ask you a few questions about your application and will automatically create a new package.json file for you. A sample process should look similar to the following screenshot:

Using npm init on Mac OS X

After creating your package.json file, you'll need to modify it and add a dependencies property. Your final package.json file should look like the following code snippet:

{
  "name": "mean",
  "version": "0.0.1",
  "description": "My First MEAN Application",
  "main": "server.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "MongoDB",
    "Express",
    "Angular",
    "Node.js"
  ],
  "author": "Amos Haviv",
  "license": "MIT",
  "dependencies": {
    "express": "latest",
    "grunt": "latest"
  }
}

Note

In the preceding code example, we used the latest keyword to tell npm to install the latest versions of these packages. However, it is highly recommended that you use specific version numbers or range to prevent your application dependencies from changing during development cycles. This is because new package versions might not be backward compatible with older versions, which will cause major issues in your application.

Installing the package.json dependencies

After creating your package.json file, you'll be able to install your application dependencies by navigating to your application's root folder and using the npm install command, as follows:

$ npm install

npm will automatically detect your package.json file and install all your application dependencies, placing them under a local node_modules folder. An alternative and sometimes better approach to installing your dependencies is to use the following npm update command:

$ npm update

This will install any missing packages and will update all of your existing dependencies to their specified version.

Updating the package.json file

Another robust feature of the npm install command is the ability to install a new package and save the package information as a dependency in your package.json file. This can be accomplished using the --save optional flag when installing a specific package. For example, to install the latest version of Express and save it as a dependency, you can just use the following command:

$ npm install express --save

npm will install the latest version of Express and will add the Express package as a dependency to your package.json file. For clarity, in the upcoming chapters, we prefer to manually edit the package.json file. However, this useful feature can come in pretty handy in your daily development cycles.

Note

It is recommended that you learn more about npm's vast array of configuration options by visiting the official documentation at https://docs.npmjs.com/files/package.json.

 

Summary


In this chapter, you learned how to install MongoDB and how to connect to your local database instance using the MongoDB shell. You also learned how to install Node.js and use the Node.js CLI. You learned about npm and discovered how to use it to download and install Node.js packages. You also learned how to easily manage your application dependencies using the package.json file.

In the next chapter, we'll discuss some Node.js basics, and you'll build your first Node.js web application.

About the Author
  • Amos Q. Haviv

    Amos Q. Haviv is a software developer, technical consultant, and the creator of MEAN.IO and MEAN.JS. He has been a full-stack developer for almost a decade and worked for multiple start-ups and enterprise companies. For the past 6 years, Amos has been working with full-stack JavaScript solutions, including Node.js and MongoDB, as well as frontend frameworks such as Angular and React. In 2013, he created the first popular boilerplate for MEAN applications, MEAN.IO, and currently continues the development of MEAN solutions at http://meanjs.org. He also gives lectures on advanced web technologies at meetups and conferences, and he guides development teams at various companies.

    Browse publications by this author
Latest Reviews (9 reviews total)
Awesome. Just it needs to be revised.
The book covers the basic and goes into details with ease. I am a novice on javascript, but I am able to follow the book. Overall, a very well structured book.
Good bargain and prompt arrival.
MEAN Web Development - Second Edition
Unlock this book and the full library FREE for 7 days
Start now