Web Application Development with MEAN
By Amos Q. Haviv, Adrian Mejia and Robert Onodi
()
About this ebook
Read more from Amos Q. Haviv
MEAN Web Development Rating: 5 out of 5 stars5/5MEAN Web Development - Second Edition Rating: 0 out of 5 stars0 ratingsAngularJS: Maintaining Web Applications Rating: 1 out of 5 stars1/5Web Application Development with MEAN Rating: 0 out of 5 stars0 ratings
Related to Web Application Development with MEAN
Related ebooks
Node Web Development, Second Edition Rating: 0 out of 5 stars0 ratingsWeb Development with MongoDB and NodeJS - Second Edition Rating: 0 out of 5 stars0 ratingsMastering JavaScript Single Page Application Development Rating: 0 out of 5 stars0 ratingsNode.js Web Development - Third Edition Rating: 2 out of 5 stars2/5Learn NodeJS in 1 Day: Complete Node JS Guide with Examples Rating: 3 out of 5 stars3/5Node.js Design Patterns Rating: 4 out of 5 stars4/5Mongoose for Application Development Rating: 5 out of 5 stars5/5Node.js Design Patterns - Second Edition Rating: 4 out of 5 stars4/5Modern JavaScript Applications Rating: 0 out of 5 stars0 ratingsMastering Java: A Comprehensive Guide to Programming Excellence Category Rating: 0 out of 5 stars0 ratingsMobile Application Development: JavaScript Frameworks Rating: 0 out of 5 stars0 ratingsJava Spring Framework: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsNode.js Blueprints Rating: 0 out of 5 stars0 ratingsSpring MVC Cookbook Rating: 0 out of 5 stars0 ratingsWeb Development with MongoDB and Node.js Rating: 0 out of 5 stars0 ratingsBlazor in Action Rating: 0 out of 5 stars0 ratingsGetting Started with Angular - Second Edition Rating: 0 out of 5 stars0 ratingsLearn AngularJS in 24 Hours Rating: 0 out of 5 stars0 ratingsNext.js: Navigating the Future of Web Development Rating: 0 out of 5 stars0 ratingsLearning Single-page Web Application Development Rating: 0 out of 5 stars0 ratingsJavaScript at Scale Rating: 0 out of 5 stars0 ratingsjQuery Mobile Web Development Essentials - Third Edition Rating: 0 out of 5 stars0 ratingsMastering Java EE Development with WildFly Rating: 0 out of 5 stars0 ratingsIntelliJ IDEA Essentials Rating: 0 out of 5 stars0 ratingsInstant SASS CSS How-to Rating: 5 out of 5 stars5/5Express Web Application Development Rating: 3 out of 5 stars3/5Jasmine JavaScript Testing - Second Edition Rating: 0 out of 5 stars0 ratingsRESTful Java Web Services - Second Edition Rating: 0 out of 5 stars0 ratingsJava Design Patterns for Automation and Performance : Convenient Practical Reliable Rating: 0 out of 5 stars0 ratings
Internet & Web For You
Coding For Dummies Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5Six Figure Blogging Blueprint Rating: 5 out of 5 stars5/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5No Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5Podcasting For Dummies Rating: 4 out of 5 stars4/5Web Design For Dummies Rating: 4 out of 5 stars4/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsPython: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsCybersecurity For Dummies Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Surveillance and Surveillance Detection: A CIA Insider's Guide Rating: 3 out of 5 stars3/5Cybersecurity All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsWordPress For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for Web Application Development with MEAN
0 ratings0 reviews
Book preview
Web Application Development with MEAN - Amos Q. Haviv
Table of Contents
Web Application Development with MEAN
Web Application Development with MEAN
Credits
Preface
What this learning path covers
What you need for this learning path
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. Introduction to MEAN
Three-tier web application development
The evolution of JavaScript
Introducing MEAN
Installing MongoDB
Installing MongoDB on Windows
Running MongoDB manually
Running MongoDB as a Windows Service
Installing MongoDB on Mac OS X and Linux
Installing MongoDB from binaries
Install MongoDB using a package manager
Using the MongoDB shell
Installing Node.js
Installing Node.js on Windows
Installing Node.js on Mac OS X
Installing Node.js on Linux
Running Node.js
Introducing NPM
Using NPM
The installation process of NPM
Installing a package using NPM
Removing a package using NPM
Updating a package using NPM
Managing dependencies using the package.json file
Creating a package.json file
Installing the package.json dependencies
Updating the package.json file
Summary
2. Getting Started with Node.js
Introduction to Node.js
JavaScript event-driven programming
Node.js event-driven programming
JavaScript closures
Node modules
CommonJS modules
Node.js core modules
Node.js third-party modules
Node.js file modules
Node.js folder modules
Developing Node.js web applications
Meet the Connect module
Connect middleware
Understanding the order of Connect middleware
Mounting Connect middleware
Summary
3. Building an Express Web Application
Introduction to Express
Installing Express
Creating your first Express application
The application, request, and response objects
The application object
The request object
The response object
External middleware
Implementing the MVC pattern
Application folder structure
Horizontal folder structure
Vertical folder structure
File-naming conventions
Implementing the horizontal folder structure
Handling request routing
Adding the routing file
Configuring an Express application
Environment configuration files
Rendering views
Configuring the view system
Rendering EJS views
Serving static files
Configuring sessions
Summary
4. Introduction to MongoDB
Introduction to NoSQL
Introducing MongoDB
Key features of MongoDB
The BSON format
MongoDB ad hoc queries
MongoDB indexing
MongoDB replica set
MongoDB sharding
MongoDB shell
MongoDB databases
MongoDB collections
MongoDB CRUD operations
Creating a new document
Creating a document using insert()
Creating a document using update()
Creating a document using save()
Reading documents
Finding all the collection documents
Using an equality statement
Using query operators
Building AND/OR queries
Updating existing documents
Updating documents using update()
Updating documents using save()
Deleting documents
Deleting all documents
Deleting multiple documents
Deleting a single document
Summary
5. Introduction to Mongoose
Introducing Mongoose
Installing Mongoose
Connecting to MongoDB
Understanding Mongoose schemas
Creating the user schema and model
Registering the User model
Creating new users using save()
Finding multiple user documents using find()
Advanced querying using find()
Reading a single user document using findOne()
Updating an existing user document
Deleting an existing user document
Extending your Mongoose schema
Defining default values
Using schema modifiers
Predefined modifiers
Custom setter modifiers
Custom getter modifiers
Adding virtual attributes
Optimizing queries using indexes
Defining custom model methods
Defining custom static methods
Defining custom instance methods
Model validation
Predefined validators
Custom validators
Using Mongoose middleware
Using pre middleware
Using post middleware
Using Mongoose DBRef
Summary
6. Managing User Authentication Using Passport
Introducing Passport
Installing Passport
Configuring Passport
Understanding Passport strategies
Using Passport's local strategy
Installing Passport's local strategy module
Configuring Passport's local strategy
Adapting the User model
Creating the authentication views
Modifying the user controller
Displaying flash error messages
Installing the Connect-Flash module
Configuring Connect-Flash module
Using Connect-Flash module
Wiring the user's routes
Understanding Passport OAuth strategies
Setting up OAuth strategies
Handling OAuth user creation
Using Passport's Facebook strategy
Installing Passport's Facebook strategy
Configuring Passport's Facebook strategy
Wiring Passport's Facebook strategy routes
Using Passport's Twitter strategy
Installing Passport's Twitter strategy
Configuring Passport's Twitter strategy
Wiring Passport's Twitter strategy routes
Using Passport's Google strategy
Installing Passport's Google strategy
Configuring Passport's Google strategy
Wiring Passport's Google strategy routes
Summary
7. Introduction to AngularJS
Introducing AngularJS
Key concepts of AngularJS
The core module of AngularJS
The angular global object
AngularJS modules
Application modules
External modules
Third-party modules
Two-way data binding
Dependency injection
Dependency injection in AngularJS
AngularJS directives
Core directives
Custom directives
Bootstrapping an AngularJS application
Automatic bootstrap
Manual bootstrap
Installing AngularJS
Meeting the Bower dependencies manager
Configuring the Bower dependencies manager
Installing AngularJS using Bower
Configuring AngularJS
Structuring an AngularJS application
Bootstrapping your AngularJS application
AngularJS MVC entities
AngularJS views
AngularJS controllers and scopes
AngularJS routing
Installing the ngRoute module
Configuring the URL scheme
AngularJS application routes
AngularJS services
AngularJS prebundled services
Creating AngularJS services
Using AngularJS services
Managing AngularJS authentication
Rendering the user object
Adding the Authentication service
Using the Authentication service
Summary
8. Creating a MEAN CRUD Module
Introducing CRUD modules
Setting up the Express components
Creating the Mongoose model
Setting up the Express controller
The error handling method of the Express controller
The create() method of the Express controller
The list() method of the Express controller
The read() middleware of the Express controller
The update() method of the Express controller
The delete() method of the Express controller
Implementing an authentication middleware
Implementing an authorization middleware
Wiring the Express routes
Configuring the Express application
Introducing the ngResource module
Installing the ngResource module
Using the $resource service
Implementing the AngularJS MVC module
Creating the AngularJS module service
Setting up the AngularJS module controller
The create() method of the AngularJS controller
The find() and findOne() methods of the AngularJS controller
The update() method of the AngularJS controller
The delete() method of the AngularJS controller
Implementing the AngularJS module views
The create-article view
The view-article view
The edit-article view
The list-articles view
Wiring the AngularJS module routes
Finalizing your module implementation
Summary
9. Adding Real-time Functionality Using Socket.io
Introducing WebSockets
Introducing Socket.io
The Socket.io server object
Socket.io handshaking
The Socket.io configuration middleware
The Socket.io client object
Socket.io events
Handling events
Emitting events
Socket.io namespaces
Socket.io server namespaces
Socket.io client namespaces
Socket.io rooms
Joining and leaving rooms
Emitting events to rooms
Installing Socket.io
Configuring the Socket.io server
Configuring the Socket.io session
Installing the connect-mongo and cookie-parser modules
Configuring the connect-mongo module
Configuring the Socket.io session
Building a Socket.io chat
Setting the event handlers of the chat server
Creating the Socket service
Creating the chat controller
Creating the chat view
Adding chat routes
Finalizing the chat implementation
Summary
10. Testing MEAN Applications
Introducing JavaScript testing
TDD, BDD, and unit testing
Test frameworks
Assertion libraries
Test runners
Testing your Express application
Introducing Mocha
Introducing Should.js
Introducing SuperTest
Installing Mocha
Installing the Should.js and SuperTest modules
Configuring your test environment
Writing your first Mocha test
Testing the Express model
Testing the Express controller
Running your Mocha test
Testing your AngularJS application
Introducing the Jasmine framework
AngularJS unit tests
Introducing Karma test runner
Installing the Karma command-line tool
Installing Karma's dependencies
Configuring the Karma test runner
Mocking AngularJS components
Introducing ngMock
Installing ngMock
Writing AngularJS unit tests
Testing modules
Testing controllers
Testing services
Testing routes
Testing directives
Testing filters
Writing your first unit test
Running your AngularJS unit tests
AngularJS E2E tests
Introducing the Protractor test runner
Installing the Protractor test runner
Configuring the Protractor test runner
Writing your first E2E test
Running your AngularJS E2E tests
Summary
11. Automating and Debugging MEAN Applications
Introducing the Grunt task runner
Installing the Grunt task runner
Configuring Grunt
Running your application using Grunt
Testing your application using Grunt
Linting your application using Grunt
Watching file changes using Grunt
Debugging Express with node-inspector
Installing node-inspector's grunt task
Configuring node-inspector's grunt task
Running the debug grunt task
Debugging AngularJS with Batarang
Using Batarang
Batarang Models
Batarang Performance
Batarang Dependencies
Batarang options
Summary
2. Module 2
1. Getting Started with the MEAN Stack
Introducing the MEAN stack
NodeJS
ExpressJS
MongoDB
AngularJS
Installing the MEAN component
Installing NodeJS
Installing ExpressJS
Installing MongoDB
Installing AngularJS tools
The AngularJS debugger
Understanding the project structure
The file structure
Components
Testing
Tools
Package managers
Bower packages
Previewing the final e-commerce app
Homepage
Marketplace
Backoffice
Understanding the requirements for e-commerce applications
Minimum Viable Product for an e-commerce site
Defining the requirements
Summary
2. Building an Amazing Store Frontend with AngularJS
Understanding AngularJS and the client directory structure
Client-side structure
Directives
Modules
Routing with AngularUI router
Controllers and scopes
Templates
Laying out the e-commerce MVP
Products
Factories and services
Creating the products factory
Creating the marketplace
Filters
CRUD-ing products with AngularJS
Services
Controllers
Routes
Templates
Partial forms
Product New
Product edit
The product view
The product list
Styling the main page
Summary
3. Building a Flexible Database with MongoDB
Understanding MongoDB
MongoDB daemons and CLI
Mapping SQL knowledge to MongoDB
Basics concepts
Queries
Aggregators
CRUDing with Mongoose
Schemas
Create
Read
Update
Delete
Exploring a few advanced features in Mongoose
Instance methods
The static methods
Virtuals
Validations
Built-in validations
Custom validations
Middleware
Reviewing models and server-side structure
The server folder
Current Mongoose models
CommonJS Modules
The user model
Summary
4. Creating a RESTful API with NodeJS and ExpressJS
Getting started with REST
Scaffolding RESTful APIs
Bootstrapping ExpressJS
Understanding routes in ExpressJS
Testing, TDD, BDD, and NodeJS
Creating the product model
Testing the products model
Product model implementation
Implementing the Product API
Testing the API
Index action tests
Show action tests
Creating action tests
Deleting action tests
Product controller
Summary
5. Wiring AngularJS with ExpressJS REST API
Implementing a RESTful product service
Building the marketplace
Wiring the product controller with new RESTful methods
Uploading product images
Uploading files in Angular
Handling file upload on Node
Seeding products
Testing RESTful APIs in AngularJS
Unit testing
ngMock
Setting up testing
Understanding the Services tests
Testing all $resource methods
Testing the Product Controller
End-to-end testing
Cleaning the database on each e2e run
Summary
6. Managing User Authentication and Authorization
Getting started with authentication strategies
Session-based authentication
Token-based authentication – using JWT
OAuth authentication
Understanding client-side authentication
Authentication management
The signing up process
Understanding server-side authentication
Authentication with PassportJS
Initializing PassportJS
The user model
Authentication strategies and routes
Local authentication
End-to-end tests for local authentication
Authenticating with Facebook, Google, and Twitter
Summary
7. Checking Out Products and Accepting Payment
Setting up the shopping cart
Installing ngCart
Making use of ngCart directives
Add/remove to cart
The cart's summary
The checkout page and Braintree integration
Setting up Braintree endpoint and authentication
The API keys
Gateway
Controller
Router
Creating an order
Modifying the order model
Testing the order model
Using the sandbox account
Summary
8. Adding Search and Navigation
Adding search to the navigation bar
Adding product categories
Adding the sidebar
Improving product models and controllers
Catalog controller and routes
The catalog model
Seeding products and categories
Implementing the search and navigation functionality
Adding custom $resource methods
Setting up routes and controllers
Wrapping it up
How navigation works on the client side
How search works on the client side
Summary
9. Deploying a Production-ready e-Commerce App
Building for production
Application environments
Optimizations for production environments
Scaling web applications
Scaling out vertically – one server
Scaling out horizontally – multiple servers
Deploying the application to the cloud
Platform as a Service
Heroku
Virtual Private Servers and Cloud Servers
Digital Ocean
Deploying applications in a multi-server environment
Setting up the app server – NodeJS application
Setting up web server – Nginx server
Performing stress tests
HTTP benchmarking tools
ApacheBench
Benchmarking Heroku deployment
Benchmarking VPS multi-server deployment
Production architecture for scaling NodeJS
Phase 0 – one server
Phase 1 – multiple application instances in one server
Phase 2 – multiple servers
Phase 3 – Micro-services
Next steps on security
Summary
10. Adding Your Own Features with High Quality
Planning a new feature
Wire framing
Implementing the solution
The HTML page
Testing the new feature
AngularJS testing
Features backlog
Deploying a new version of the app
Zero-downtime deployments
Setting up the zero-downtime production server
Getting started with Capistrano
Installing Capistrano
Understanding Capistrano
Preparing the server
Setting up Capistrano variables
Capistrano tasks
Adding new tasks
Preparing Nginx
Load balancing
Static file server
WebSockets
Summary
3. Module 3
1. Contact Manager
Setting up the base application
Folder structure
Server-side package.json
The first application file
Creating the Express configuration file
Setting up mocha for testing
Setting up Mongoose
Managing contacts
Creating the contact mongoose schema
Describing the contact route
Creating a contact
Getting contacts
Getting a contact by ID
Updating a contact
Removing a contact
Running our tests
Implementing the contact routes
Adding all endpoints
Finding a contact by ID
Getting contact information
Updating a contact
Removing a contact
Running the contact test
Securing your application routes
Describing the password helper
Implementing the password helper
Creating the user Mongoose schema
Describing the authentication method from the user model
Implementing the authentication method
Authentication routes
Describing the authentication routes
Integrating Passport
Implementing the authentication routes
Restricting access to contacts routes
Integrating Angular 2 into our application
Granting access to our application
AuthService
User sign-in component
Custom HTTP service
The Contact module
Contact service
Contact component
List contacts component
Creating a contact component
Editing an existing contact
Finishing touch
Summary
2. Expense Tracker
Setting up the base application
Installing the dependencies
Creating the base configuration files
Creating the main server.js file
Setting up the user section
Describing the user model
Implementing the user model
Authenticating users
Describing the authentication strategies
Implementing the token generation
Persisting tokens in MongoDB
Authentication using HTTP Basic
Adding authentication routes
Verifying users using bearer authentication
Bearer strategy
Protecting resources using tokens
Tracking expenses
Monetary values
The category model
Categories routes
Getting the category by ID
Creating a category
Getting one and all categories
Updating and deleting a category
Defining the expense model
Describing the expense module functionality
CRUD operations for expenses
Create expense
Get expense by ID
Get one expense
Get all expenses
Update expense
Delete expense
Getting the expense balance
Implementing the Angular client application
Bootstrapping the project
Registering users
The auth service
Register component
Sign-in-user component
Common functionalities
Custom HTTP service
Using a single export file
The categories module
Category service
The categories component
Create a new category
List all categories
The category component
The expenses module
Expense service
Filter expenses
Add a new expense
List expenses
Display balance
Expenses component
Summary
3. Job Board
Setting up the base application
Modifying the user backend
Modifying the user model
An authorization policy
The company backend module
The company model
The company controller
Creating a company
Getting a company by ID
Getting all companies
Updating a company
Adding a company member
Removing a company member
Company routes
The job backend module
The job model
Job controller
Adding a new job for a company
Finding a job by ID
Getting all jobs
Updating a specific job
Job routes
Getting one and all jobs
Creating a route
Updating a route
Job applications
The application model
Controller logic
Applying for a job
Finding a given application by ID
Getting all job applications
Updating an application
Removing an application from a job
Creating a new company
The company service
Creating a company component
Displaying companies
The job module
The job service
The job base component
The jobs component
The job list component
Job details
Adding new jobs
Company details
User profile
Profile backend
Synchronizing profile data
Editing profile data
The profile block component
Extra models
Summary
4. Chat Application
Setting up the base application
Modifying the user model
The message history data model
The thread schema
The message schema
Thread backend
Thread controller
Defining routes
Message controller
Backend chat service
Chat service implementation
Instant messaging module
Bootstrapping the Angular app
The boot file
App component
Custom data types
User type
Thread type
Message type
Application services
User service
The thread service
The message service
The chat component
The user list component
Displaying threads
Thread component
Thread list component
Messaging
Sending messages
The message component
The message list component
Summary
5. E-commerce Application
Setting up the base application
Data modeling
Custom money data type
The product model
The order model
The inventory model
The core Service Layer
The product catalog
The inventory manager
Shopping cart
The Auth micro app
Defining the class
The controller
Exposing an API
The Api class
Product controller
Product router
Shared resources
The admin section
The admin micro app
Changing the auth module
Products administration
The product service
List products
The main product component
Add and edit a product
Order handling
Retrieving orders
View and update orders
Building the Storefront
Storefront micro app
Storefront pages
Main layout
List products
Summary
6. Auction Application
Setting up the base app
What we are building
Data modeling
Auction
Bidder
Auction backend
The Mediator
Auction manager
Auctioneer
Using the service from controller
Accessing data from the e-commerce API
E-commerce client service
Frontend services
Auction service
The socket service
The bid service
The bidder service
The Auction module
The base component
The auction list
The detail page
The bid module
Listing bids
The bid component
Summary
A. Bibliography
Index
Web Application Development with MEAN
Web Application Development with MEAN
Unlock the power of the MEAN stack by creating attractive and real-world projects
A course in three modules
BIRMINGHAM - MUMBAI
Web Application Development with MEAN
Copyright © 2016 Packt Publishing
All rights reserved. No part of this course may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this course to ensure the accuracy of the information presented. However, the information contained in this course is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this course.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this course by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Published on: October 2016
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78712-172-0
www.packtpub.com
Credits
Authors
Amos Q. Haviv
Adrian Mejia
Robert Onodi
Reviewers
Clay Diffrient
Liran Tal
Vikram Tiwari
Yutaka Yamaguchi
Carlos De la Rosa
Dan Shreim
Content Development Editor
Samantha Gonsalves
Graphics
Jason Monteiro
Production Coordinator
Aparna Bhagat
Preface
The MEAN stack (MongoDB, Express.JS, AngularJS, and Node.JS) is a killer JavaScript full stack combination. It provides agile development without compromising on performance and scalability. It is ideal to build responsive applications with a large user base.
All topics in this course have been covered in individual modules so that you develop your skill after the completion of a module and get ready for the next. Through this comprehensive course, you'll learn how to use MEAN for web development from scratch to finish!
The first module will help you set up your environment and explain how to connect the different MEAN components together using the best modules. You'll be introduced to the best practices of maintaining your code clear and simple and how to avoid common pitfalls. We'll walk through building your authentication layer and adding your first entity. You'll learn how to leverage JavaScript nonblocking architecture in building real-time communication between your server and client applications. Finally, we'll show you how to cover your code with the proper tests and what tools to use to automate your development process.
The second module will teach you how to create your own e-commerce application using the MEAN stack. It will take you step by step through the process of learning and building parallelly. Using this guide, you will be able to show a product catalog, add products to shopping carts, and perform checkouts. It will cover product categorization, search, scalable deployment, server setups, and other features. At the end of this module, you will have a complete e-commerce application that is fully tested, scalable, and alive. Additional topics on how to scale the application, server deployment, and security will also be discussed.
In the last leg of this course, serves as a guide and a higher perspective of applications built using the MEAN stack. It is a showcase of different scenarios of building applications using the MEAN stack. Probably it's not the only way of doing things, but it should provide you with a starting point, or give you an insight into how certain parts of an app are built.. It will jump right into action and showcase six built-from-the-beginning applications, each with different use cases and solving a high-level problem.
What this learning path covers
Module 1, MEAN Web Development, Starting with MEAN core frameworks, this project-based 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. Finally, you will walk through the different tools and frameworks that will help expedite your daily development cycles.
Module 2, Building an E-Commerce Application with MEAN, This module will show you how to create your own e-commerce application using the MEAN stack. It will take you step by step through the parallel process of learning and building. It will also teach you to develop a production-ready, high-quality e-commerce site from scratch and will provide the knowledge you need to extend your own features to the e-commerce site. By the end of the module, you will be able to build and use your own e-commerce app in the real world and will also be able to add your own new features to it.
Module 3, MEAN Blueprints, each chapter in this module covers a complete, single, advanced end-to-end project. You'll learn how to build complex real-life applications with the MEAN stack and few more advanced projects. You will become familiar with WebSockets and build real-time web applications, as well as create auto-destructing entities. Later, we will combine server-side rendering techniques with a single page application approach. You'll build a fun project and see how to work with monetary data in Mongo. You will also find out how to a build real-time e-commerce application. By the end of this course, you will be a lot more confident in developing real-time, complex web applications using the MEAN stack.
What you need for this learning path
Module 1:
This module is suitable for beginner and intermediate web developers with basic knowledge in HTML, CSS, and modern JavaScript development.
Module 2:
For this module, you need a basic understanding of JavaScript, HTML, and CSS. You will also need the following tools:
A text editor or IDE (for example, Sublime Text, Cloud9, Eclipse, Notepad++, Vim, and so on)
A command-line terminal
NodeJS (https://nodejs.org/)
MongoDB (https://www.mongodb.org/)
Accounts on social network (for example, Facebook, Twitter, or Google+) and, optionally, accounts on PayPal.
Access to a cloud server, either Heroku, Digital Ocean, or similar.
Module 3:
You will require any modern web browser (such as Chrome's latest version or IE 10+), the Node.js platform installed on your machine, and version 3.2 or higher of MongoDB. Optionally, you can install any web server, such as Nginx, Apache, IIS, or lighttpd, to proxy requests to your Node.js application.
Who this learning path is for
This learning path is for web developers who are experienced in developing applications using JavaScript. This course is for developers who are interested in learning how to build modern and multiple web applications using MongoDB, Express, AngularJS, and Node.js.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this course—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the course's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt course, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this course from your account at http://www.packtpub.com. If you purchased this course elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the course in the Search box.
Select the course for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this course from.
Click on Code Download.
You can also download the code files by clicking on the Code Files button on the course's webpage at the Packt Publishing website. This page can be accessed by entering the course's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the course is also hosted on GitHub at https://github.com/PacktPublishing/Web-Application-Development-with-MEAN. We also have other code bundles from our rich catalog of course and videos available at https://github.com/PacktPublishing/. Check them out!
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our courses—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this course. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your course, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the course in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this course, you can contact us at <[email protected]>, and we will do our best to address the problem.
Part 1. Module 1
MEAN Web Development
Master real-time MEAN web application development and learn how to construct a MEAN application using a combination of MongoDB, Express, AngularJS, and Node.js
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, AngularJS 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 module, we 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 Node's package manager. In this chapter, we're going to 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 Node.js Package Manager (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 of implementing this model is the MVC architectural pattern. In the MVC paradigm, the logic, data, and visualization are separated into three types of objects, 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 MVC is shown in the following diagram:
Common MVC architecture communication
In the 25 years of web development, many technology stacks became popular 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, which 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. But 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. AngularJS along with other MVC 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 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.
Introducing MEAN
MEAN is an abbreviation for MongoDB, Express, AngularJS, 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?
What kind of JavaScript development tools can you use to expedite your MEAN application development process?
In this module, I'll try to answer these questions and many more, but before we can 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, 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
The MongoDB versioning scheme works in such a way that only even version numbers mark stable releases, and so versions 2.2.x and 2.4.x are stable, while 2.1.x and 2.3.x are unstable releases and should not be used in production. The latest stable version of MongoDB is 2.6.x.
When you visit the download page at http://mongodb.org/downloads, you'll be offered a download of an archive containing 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 in (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, unpack the archive file, and move the folder to C:\mongodb. MongoDB uses a default folder to store its files. On Windows, the default location is C:\data\db, so in the command prompt, go to C:\ and issue the following command:
> md 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 moved the MongoDB files to the right folder and 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 issue the following command:
> C:\mongodb\bin\mongod.exe
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 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:\mongodb\log
Then, you'll be able to create a configuration file using the --logpath command-line flag, so in the command prompt, issue the following command:
> echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg
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. In the new command prompt window, install the MongoDB service by running the following command:
> sc.exe create MongoDB binPath= \"C:\mongodb\bin\mongod.exe\" --service --config=\"C:\mongodb\mongod.cfg\"
DisplayName= MongoDB 2.6
start= auto
If the service was successfully created, you will get the following log message:
[SC] CreateService SUCCESS
Notice that the install process will only succeed if your configuration file is set correctly and contains the logpath option. 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-2.6.4.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-2.6.4.tgz
Now, change the name of the extracted folder to a simpler folder name by running the following command:
$ mv mongodb-osx-x86_64-2.6.4 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
Note
You may experience some troubles 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 of your home folder, so do 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
Install MongoDB using a package manager
Sometimes the easiest way to install MongoDB is by using a package manager. The downside is that some package managers are falling behind in supporting the latest version. Luckily, the team behind MongoDB also maintains the official packages for RedHat, Debian, and Ubuntu, as well as a Hombrew 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
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 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
The Node.js version scheme works in a way similar to that of MongoDB, where even version numbers mark stable releases, and so versions 0.8.x and 0.10.x are stable, while 0.9.x and 0.11.x are unstable releases and should not be used in production. The latest stable version of Node.js is 0.10.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 the http://nodejs.org/download/ page 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 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 http://nodejs.org/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 offer 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/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-v0.10.31.tar.gz $ cd node-v0.10.31 $ ./configure && make && sudo make install
If everything goes well, this will install Node.js on your machine. Note that these commands are for the Node.js 0.10.31 version, so remember to replace the version number to the version you downloaded. If you encounter any problems, the team behind Node.js has created a set of alternative installation options for you, documented at https://github.com/joyent/node/wiki/installation.
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 successfully installed Node.js, you will now 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!'); 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 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 the NPM. NPM has the following main features:
A registry of packages to browse, download, and install 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're going to 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://npmjs.org/.
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 you learn more about npm by visiting the official documentation at https://npmjs.org.
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 the third-party packages in a local node_modules folder placed inside your application folder. It has no effect system-wide, 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 packages you want Node.js to use globally. Usually these are CLI tools, such as Grunt, that you'll meet 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
Installing a module globally is similar to its local counterpart, but you'll have to add the –g flag as follows:
$ npm install –g
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
For instance, to install the second major version of the Express package, you'll need to issue the following command:
$ npm install [email protected]
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/isaacs/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, and so you'll need a better way to manage these package 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
,
scripts
: {
test
: echo \"Error: no test specified\" && exit 1
},
keywords
: [
MongoDB
,
Express
,
AngularJS
,
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 will install all your application dependencies, placing them under a local node_modules folder. An alternative and sometimes better approach to install 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 issue 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 reasons, in the upcoming chapters, we'll 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 configuration options by visiting the official documentation at https://npmjs.org/doc/json.html.
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.
Chapter 2. Getting Started with Node.js
In the previous chapter, you set up your environment and discovered the basic development principles of Node.js. This chapter will cover the proper way of building your first Node.js web application. You'll go through the basics of JavaScript event-driven nature and how to utilize it to build Node.js applications. You'll also learn about the Node.js module system and how to build your first Node.js web application. You'll then proceed to the Connect module and learn about its powerful middleware approach. By the end of this chapter, you'll know how to use Connect and Node.js to build simple yet powerful web applications. We'll cover the following topics:
Introduction to Node.js
JavaScript closures and event-driven programming
Node.js event-driven web development
CommonJS modules and the Node.js module system
Introduction to the Connect web framework
Connect's middleware pattern
Introduction to Node.js
At JSConf EU 2009, a developer named Ryan Dahl went onstage to present his project named Node.js. Starting in 2008, Dahl looked at the current web trends and discovered something odd in the way web applications worked. The introduction of the AJAX technology a few years earlier transformed static websites into dynamic web applications, but the fundamental building block of web development didn't follow this trend. The problem was that web technologies didn't support two-way communication between the browser and the server. The test case he used was the Flickr upload file feature, where the browser was unable to know when to update the progress bar as the server could not inform it of how much of the file was uploaded.
Dahl's idea was to build a web platform that would gracefully support the push of data from the server to the browser, but it wasn't that simple. When