Full Stack JavaScript Development With MEAN: MongoDB, Express, AngularJS, and Node.JS

Views: 247
Ratings: (0)

With modern tools. it is possible to create a production grade, full-stack application using HTML, CSS, and JavaScript alone. The combination of MongoDB, Express, AngularJS, and Node.js has become so popular that it has earned the title MEAN stack -- the subject of this book.

This book explores the MEAN stack in detail. We will begin by covering Node.js, as it will lay the groundwork for all of our server-side work. You will learn how to get Node running on your local machine as well as download modules using npm. The key aspects of the Node.js programming model will also be covered.

From there, we will move on to MongoDB, where you'll learn how to interact with Mongo from a Node application. You will also learn how to create, retrieve, update, and delete data from a Mongo store.

After you have a solid grasp on Node and Mongo, the book will move on to the Express web server. We'll cover the basics of Express applications via topics like routes and middleware. Building on previous chapters, we will cover the integration of Node, Mongo, and Express.

Our coverage of the MEAN stack will wrap up with several chapters on AngularJS. These chapters will cover Angular fundamentals like data binding, directives, controllers, routing, and services. In an effort to explore competing technologies, a slight introduction to Ember.js will also be provided.

Full stack JavaScript is not fully encompassed by the MEAN stack. There is an entire ecosystem of JavaScript tools to learn about, and this book will introduce a few of them. We will cover task runners Gulp.js and Grunt.js which are extremely useful for automating mundane, repetitive tasks. We'll also cover JSHint, a linting tool used to improve code quality. Linting tools analyze source code and report potentials issues - a feature that is especially useful in non-compiled languages like JavaScript.

List price: $29.00

Your Price: $23.20

You Save: 20%

 

22 Slices

Format Buy Remix

2. Node.js Introduction

ePub

To date, there have been over ten different server-side implementations of JavaScript. While Node.js is the most successful, it is far from being the first. Engineers have spent considerable time and effort trying to make JavaScript run on a web server—but why? What is it about JavaScript that makes it so well-suited to being a server-side language? Ultimately, it boils down to two factors: familiarity and non-blocking asynchronous I/O.

Looking at GitHub usage, JavaScript is the prevailing language. As evidenced in Figure 2.1, the raw amount of JavaScript code continues to grow, outpacing all the other popular scripting languages available today. The graph represents the number of new GitHub repositories created that list JavaScript as the primary language.

Figure 2.1. New GitHub repositories by language

JavaScript was created in 1995 by Brendan Eich during his time at Netscape Communications Corporation. By 1996, the official ECMA specification had been submitted with both Microsoft and Netscape implementing JavaScript in their flagship browsers. Over the subsequent twenty years or so, there have been new versions of the ECMAScript specification, JavaScript libraries such as jQuery, client-side JavaScript MVC frameworks, JavaScript controlling robots with Tessel, and the rise of server-side JavaScript. If you have ever worked on a web page in the last twenty years, you’ve had some exposure to JavaScript.

 

3. Modules and npm

ePub

As we discussed in Chapters 1 and 2, one of the keys to the success of Node is the wide array of modules that are available to developers. There are open-source modules on GitHub for the majority of problems developers face when building a web server. Then there are modules available for social authentication, validation, and even server frameworks such as ExpressJS and Hapi. Not every module is massive and complicated, though; there are simple modules for coloring console text, formatting dates and times, and cloning JavaScript objects.

As developers, we try not to reinvent the wheel if we can help it. We preach “code reuse” constantly and Node does not disappoint in this area. To fully appreciate the Node ecosystem, it is important to understand how modules and the Node package manager (npm) function.

npm is the package manager for Node. It is a Node module that is installed globally with the initial installation of Node. By default, it searches and loads packages from the npm registry. In addition to being a package registry, it also acts as a user-friendly resource for developers to discover new modules. npm is the heart of the Node module ecosystem, so let’s now discuss some of the commands you need to know to use it effectively.

 

4. Node’s Programming Model

ePub

A language’s programming model defines how developers write code, and can make or break a language. Since Node is just JavaScript, the rules of the language are the same; however, Node does adhere to a number of additional conventions that make code consistent across its core and third-party modules. In Chapter 2, you learned how to create a simple HTTP server in Node. The goal of this chapter is to help you better understand the code structure of that server so you can extend it to other Node applications.

The most important concept to understand about JavaScript, and Node by extension, is that it is single-threaded. This means that JavaScript applications can only perform one task at a time. They can, however, give the illusion of being multi-threaded through the use of an event loop. Essentially, the JavaScript engine maintains several queues of unhandled tasks. These queues include things such as events, timers, intervals, and immediates. Each execution of the event loop, known as a cycle, causes one or more tasks to be dequeued and executed. As these tasks execute, they can add more tasks to the internal queues. Each cycle is made up of smaller steps, known as ticks. An example of a tick would be the act of accessing an item from timer queue.

 

5. Core Modules

ePub

In Chapter 3, you learned about Node’s module system and the require() function. Then, Chapter 4 taught you how to write code in the Node way. Along the way, you’ve also seen a few examples that used the http and fs core modules. This chapter brings all the previously discussed material together, explaining how to use some of Node’s core modules in detail. Before we start, it’s worth pointing out that we’ll only scratch the surface of the Node core—it’s far too large to cover in a single chapter; however, after completing this chapter, you should have adequate knowledge to understand the Node documentation.

Reading arguments from the command line is extremely simple in Node. All command line arguments passed to a Node application are available via the process.argv array. Note that the first two elements of this array are the node executable, followed by the name of the invoked JavaScript file. This means that the actual application arguments begin at process.argv[2]. Listing 5-1 shows how command line arguments are accessed and printed to the console using the forEach() method. To run this example, save the code in a file named argv-demo.js, and run node argv-demo foo bar baz:

 

6. Building the Node Server

ePub

We’ve covered everything you need to dive into creating a real Node server in the preceding chapters. This chapter will focus on building a subset of the Node server for the human resources application we’re using to demonstrate the MEAN stack.

Before you start writing any code, you need to have a basic idea of what your web server should do. For this subset example, our server will need to do two tasks: view employee information as a list, and for an individual. The server must also be able to send static resources such as CSS, client-side JavaScript, images, and HTML files. We should strive to make the various employee resources RESTful rather than use SOAP/WSDL. As we delve further into the development of our Human Resources application, you’ll find that hooking in different front-end frameworks such as Angular is much easier with a RESTful API that's simple to consume. The RESTful design pattern also lines up cleanly with the employee operations we require for our application, namely create, retrieve, update, and delete (CRUD). We should have the static resources segmented out into their own folder and break the code up into logical and reusable pieces.

 

7. MongoDB Introduction

ePub

Almost all web applications depend on some sort of database for persisting information. Databases are primarily either relational or NoSQL. Relational databases, the de facto standard for years, are identified by their use of SQL. The NoSQL family of databases, as their name suggests, do not use SQL, and have risen to prominence in recent years, mainly due to the perceived ease of use and speed. The MongoDB documentation provides a very good comparison of (Mongo-specific) NoSQL commands to SQL. The next three chapters will discuss MongoDB, one of the most popular NoSQL databases, while relational databases will be explored in Chapter 10.

The name NoSQL is a bit generic, referring to a number of data store types. Essentially, NoSQL represents any data store that does not use SQL. Some example types of NoSQL databases are document stores, object stores, and key/value stores. Examples of NoSQL implementations are Redis, Memcached, Cassandra, and, of course, MongoDB. None of these follow the table-based setup of relational databases.

 

8. Interacting with MongoDB Using Mongoose

ePub

The previous chapter covered the basics of MongoDB: what it is, how to set it up, and how it can be useful. We’ll assume that by this point you have a MongoDB instance up and running somewhere. We’re going to use the instance we’ve created, but you should create your own so that you have the freedom to experiment on your own. If you’re yet to do so, you can create a free MongoDB instance at MongoLab.

In this chapter, we’re going to cover the nuts and bolts of working with MongoDB. If you remember previous chapters, we used the term CRUD (create, retrieve, update, and delete). CRUD operations cover the majority of data interactions in most computer systems. When you understand the basic CRUD features of MongoDB, you’ll be surprised at how much you can accomplish with very little code.

For this chapter, we’re going to keep all of our code in a single file for clarity. We’ll just keep appending and editing the same file, and end up with a database priming script for future use in this book.

 

9. Using MongoDB and Mongoose in Our Sample App

ePub

In Chapter 6, we began work on our example human resources application. At the time, Node was unfortunately the only technology that had been introduced, so the application in Chapter 6 only consisted of a Node HTTP server returning hard-coded employee data from a JSON file. Now that we have a good understanding of MongoDB and the Mongoose module, we can update the example application to use a database.

This chapter will build on the server from Chapter 6. We’re going to assume that you have the example application code on your local machine already. We’ll also assume that you have run npm install, and can successfully connect to the server using a browser. For example, you should be able to view the employee listing shown in Figure 9.1 by visiting the URL http://127.0.0.1:1337/employees.

Figure 9.1. Output data from the example application

We’re going to begin by creating two Mongoose models for working with our MongoDB instance. The first step is to install the mongoose module and save it to the project’s package.json using the command shown in Listing 9-1:

 

10. Alternatives to Mongo

ePub

MongoDB is a fantastic technology, but it is far from being the only option when it comes to adding a data store to your applications. There are a number of NoSQL alternatives such as Redis, CouchDB, and Cassandra. Alternatively, you could turn to a relational database management system such as MySQL, Oracle, or SQL Server. Using a relational database will require you to understand SQL, but picking up the basics of SQL is relatively easy. This chapter explores MySQL as a free, relational alternative to MongoDB. Technically, this deviates from the MEAN stack, but we feel strongly about exploring popular and viable alternatives.

Relational databases are still hugely popular, despite the rise of NoSQL alternatives. According to the db-engines.com rankings, the four most popular databases—Oracle, MySQL, SQL Server, and PostgreSQL—are all relational databases. So if this book were to ignore relational databases, we’d be doing a huge disservice to our readers. Many people—the authors of this book included—actually prefer relational databases due to SQL’s simplicity, guaranteed data consistency, and extensive support of data joins.

 

11. Introduction to Express

ePub

We touched on Express earlier, but now we’re going to really dive into it. Express is a Node module that provides a thin web application framework around the core Node modules discussed in Chapter 5. As of this writing, it is the most starred module on the npm registry.

A Google search for “getting started with Node” will almost always lead you to installing and using Express. It is a very mature and community-tested framework. The first version of Express (1.0.0) was released in November 2010 after going through several beta and release candidate versions. The lead developer of Express from beta though version 3 was TJ Holowaychuk who worked alongisde a few key members of the GitHub community. After version 3, Holowaychuk became less involved with its daily development, handing the reins to a group of core GitHub community members. In July 2014, Holowaychuk handed ownership of Express to a Node startup company named StrongLoop. StrongLoop continues to keep Express open source, and the majority of the core community still work with StrongLoop on the steady development of Express.

 

12. Architecture of an Express Application

ePub

In the previous chapter, we generated our first Express application. At the time of writing, Express was in version 4 so that’s the version this book will be discussing. The Express generator gives developers a great place to start building a new web server. It provides a few simple routes, Jade templating integration, cookie and body parsing, and static file serving. In this chapter, we’ll cover the important files and concepts of the generated Express application. This will give you a strong understanding of the architecture of the Express ecosystem, as well as the interactions in many of the framework’s moving parts.

The first thing you’ll probably notice is that if you run node app.js, nothing happens. The generator created a bin folder with a www file inside of it. The intention is to use this to start the server instead of app.js. To start your server, run node bin/www. You can also run npm start as well because that command has been entered into package.json. Once the server is running, point a web browser to localhost:3000 and you should be greeted with a simple welcome page.

 

13. Using Express in Our App

ePub

This chapter revisits the example Human Resources application that was started in Chapter 6 and continued in Chapter 9. Up to this point, we've created a Node application that communicates with a MongoDB store. We used Node's http module to write a custom implementation for a router. Now that we have the more powerful Express router at our disposal, we're going to replace our http code.

If we were starting a new application from scratch, we would likely want to use a scaffolding generator, such as Yeoman (which has a MEAN stack generator); however, since we're updating our existing application, we're going to modify everything by hand.

The first step in our migration to Express is to update the package.json file. We need to install Express and several pieces of middleware. We can install all the necessary modules using the command in Listing 13-1:

Listing 13-1. Installing Express and other required middleware

 

14. Alternative Server Frameworks

ePub

With a language as popular as JavaScript, there are bound to be differences in opinion on how to solve any problem— from something as simple as loop optimization to the more complex, such as the best way to simulate classical object-oriented inheritance. The passion and drive to perform tasks the best way followed JavaScript enthusiasts into the Node community, and is evident when looking at the available web server frameworks. A few quick Google searches and you’ll see that the list of available frameworks is quite large, while a search for “framework http” on npm nets you page after page of various web server frameworks. There are far too many options to name here without doing any of them a disservice.

In this chapter we’re going to focus on hapi, an alternative to the Express framework. We’ll look at hapi because it’s the second-most popular Node framework, and it’s very different from Express.[4]

The hapi server framework has an active and growing community, as well as many big name supporters. At the time of writing, hapi is the second-most starred server framework on the npm registry and is quickly becoming more popular. hapi’s approach is to be configuration-centric instead of development-centric. This allows developers to focus more on business logic than the nuts and bolts of a web server and an evergrowing list of middleware functions.

 

15. AngularJS Overview

ePub

The final MEAN technology that we’re going to explore is AngularJS. Angular is a front-end framework used for creating single-page applications (SPAs). Like the other MEAN technologies, Angular is open source and can be used freely in your applications.

Angular was created in 2009 by Miško Hevery and Adam Abrons at a company named Brat Tech LLC. Angular was initially intended to be part of an online JSON storage service, but this concept was abandoned and Angular was released to the open-source world. Adam Abrons has since left the project, but Hevery continues work on the project. Hevery became employed by Google, which is now closely associated with Angular.

Single-page applications represent the latest evolution in web design. The idea behind SPAs is that all the necessary code can be retrieved in a single page load or dynamically loaded as necessary. As the user interacts with the application, data is sent to and received from the server using Ajax requests. This provides a more fluid user experience than page reloads, and is closer to resembling a native application. Some of the common characteristics of SPAs will now be explored:

 

16. Data Binding

ePub

In programming, data binding is the automatic synchronization of data is between a program’s data layer and the associated view layer. Think back to some of the database code in this book. We would execute a query in the database, collect the result in a variable, and then send the JSON to the requesting client. If we take this one more logical step, that JSON would be used by the display layer to show the database results to the user. This can be thought of as one-way data binding; the data from the database is bound to the view we display to the user. For our purposes, our application is going to be a web page and the view is going to be HTML.

One of the marquee features of Angular is the built-in two-way data binding system. This allows Angular developers to create rich, interactive web applications with very little UI code. (In fact, later on in the chapter, Listing 16-1 will provide a nontrivial interface with zero JavaScript.) In this chapter, we’re going to discuss one- and two-way data binding, and walk through some Angular code examples to demonstrate leveraging this powerful feature.

 

17. Angular Directives

ePub

This chapter continues our exploration of Angular’s core principles. Specifically, this chapter focuses on directives, which are what allow Angular to extend HTML syntax. Angular ships with a number of built-in directives, but developers can also define custom directives to suit their application’s needs. This chapter will explain how to use directives, as well as how you can create your own.

Let’s begin by defining exactly what is a directive. According to the official documentation:

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

In other words, directives are additional pieces of markup that Angular interprets to extend the default behavior of HTML. Directives can be specified as custom HTML elements, attributes, classes, or comments. For example, given a fictional directive named ngFoo, Listing 17-1 shows how it can be used as an element, attribute, class, and comment:

 

18. Controllers

ePub

Controllers create a framework to promote code reusability and testability. They are the basic building blocks of an Angular application. In previous chapters, we covered data binding and directives. We briefly touched on Angular controllers at the end of Chapter 16. In this chapter, we’re going to cover controllers in greater detail. We’ll discuss what they are and what purpose they serve; we will then cover some syntax issues, best practices, and examples.

Like everything related to Angular, it is important to remember that controllers are just JavaScript functions. These functions are used to create a new Angular (or scope) context and are bound to sections of HTML markup. A controller provides a place to put application and view logic that is specific to a particular set of HTML tags. Keep in mind that a single view can use multiple controllers: the view to controller relationship is not one-to-one. It is also possible to reuse controllers in different views.

 

19. Client-side Routing

ePub

In Chapter 18, we demonstrated how to make Ajax requests to our Express server and load the results into $scope to display the results. That’s great for a single-page website, but most applications span more than a single page. In Listing 18-2, what if we wanted to add a new screen that could be used to edit an employee? The application needs to change pages and display a new view, but we want to use the benefits of an Ajax request and not lose all of our JavaScript state and static files in the browser’s memory. We also want that page to be bookmarkable, so the page has to be stateless.

This is where client-side routing really shines. Client-side routing allows developers to create standard anchor tags throughout the HTML that will be handled by the Angular router. The Angular router intercepts these links before they are sent to the web server and runs them through a client-side routing table, responding with a new page of content. The new page can have its own Angular controller and completely new block of HTML. To the user, it appears exactly the same as traditional navigation, except the change is almost instant.

 

Load more


Details

Print Book
E-Books
Slices

Format name
ePub (DRM)
Encrypted
true
Sku
9781457192340
Isbn
9781457192340
File size
0 Bytes
Printing
Disabled
Copying
Disabled
Read aloud
No
Format name
ePub
Encrypted
No
Printing
Allowed
Copying
Allowed
Read aloud
Allowed
Sku
In metadata
Isbn
In metadata
File size
In metadata