Chapter 7. Leveraging the MEAN Stack

The MEAN stack is an acronym for MongoDB, Express, AngularJS, and Node.js. It represents full stack development using practically nothing but JavaScript alone. Naturally, you will need some HTML and CSS to render things to the browser and make them look pretty.

MongoDB is a document-based NoSQL database that stores data in ways that can be treated like plain JavaScript objects. As the data and database methods are essentially JavaScript, MongoDB plays well with JavaScript-based applications.At this point, if you typed the code correctly, there will be no output in the console other than a new line. Open your favourite browser 

Express is a web application framework, written in JavaScript that runs beautifully on Node.js. It's similar to other frameworks, such as Sinatra, but less obtrusive and opinionated. Express is essentially routing and middleware that handles web requests and responses.

AngularJS is a frontend JavaScript framework that is primarily used to build Single Page Web applications. It's a powerful and prescriptive framework curated by Google, which has become one of the more popular JavaScript MV* toolkits.

In this chapter, you'll explore each of the following components of the MEAN stack while starting to build the framework of your very own Single Page Application:

  • Running Node.js code from the command line using the REPL
  • Writing and running Node.js scripts
  • Installing MongoDB and basic CRUD operations from the Mongo shell
  • Installing Express via the standard method and the Express generator
  • Express routing, middleware, and view rendering
  • Building the basic components of a frontend application with Angular

The Node.js environment

Node.js is a runtime environment built to execute JavaScript. With it, you can build powerful software, such as full-fledged backend web servers. In Chapter 1 , Getting Organized with NPM, Bower, and Grunt, you began to use some Node.js-based tools, such as Grunt, NPM, and the Node Package Manager.

Node.js is powerful, and extremely fast. It is based on the V8 JavaScript engine that's used in the Chrome browser and is tuned for speed. It uses a non-blocking I/O that allows it to handle many requests simultaneously.

This chapter assumes that you have already installed the Node runtime. If not, go to https://nodejs.org, and follow the installation instructions for your operating system Node version 4.3.2 has been used in this book.

Running the REPL

Node.js provides a way to enter a run JavaScript code from the command line called the Read-Eval-Print Loop or REPL. You can start the REPL simply by typing node at the command line in a console. It's a great way to begin exploring some of the possibilities with Node.js, as shown in the following command:

$ node
> var sum = 1 + 2;
undefined
> sum
3
console.log(sum);
3
undefined

Note

The variable assignment in JavaScript returns undefined.

Here, it might appear that there are two return values, the first being 3 and the second being undefined. In this case, console.log() is a function that is used to write things out to the screen, but the function actually returns undefined. This will be useful in writing Node.js code where you want to log things to the screen, similar to print statements in other programming languages.

To quit out of the REPL, hit Ctrl + C twice.

Writing a hello Node.js script

Using the REPL on its own will not be incredibly useful. Node.js allows developers to create programs by writing them out and saving them as text files with a .js file extension.

One of the advantages of this is that you can use any text editor and practically any IDE to write Node.js programs.

To show you how powerful Node.js can be, let's start by building a simple web server. It will not do much, other than handling HTTP requests, but it's a great start.

Let's create a new file, call it hello.js, and open it in your favorite text editor or text-based IDE. Then, type the following lines of code:

var http = require('http'); 
var serverResponse = function(req, res){ 
    res.end("Hello Node"); 
} 
 
var server = http.createServer(serverResponse); 
server.listen(3000); 

Save the file and navigate it to the directory where it is stored with a console program. Then, type the following command:

$ node hello

At this point, if you typed the code correctly, there will be no output in the console other than a new line. Open your favorite browser and type localhost:3000 in your address bar.

You should see Hello Node in your browser's main window. And just like that, you have written a web server.

You can stop the server by typing Ctrl + C in the console.

There's a lot going on in a small piece of code, so let's walk through what the program is doing:

  • In the first line of the varhttp=require('http'); code, similar to import statements in some programming languages, Node.js uses require to import code modules. Node.js ships with a number of built-in code modules. The HTTP module is a built-in module that provides, as you might assume, HTTP services. Built-in modules can be required using a string containing the name of the module. Generally, they will be used by assigning them to a variable. Non-built-in modules are required using a string containing the full path to the module.
  • In the next two lines, var serverResponse = function(req, res) and res.end("Hello Node"), the serverResponse function here is a callback function that we will pass to the web server we are creating. We will cover the request and response objects in more detail when we get into Express.js, but it's important to realize that we are setting up req to deal with the HTTP request object, and res to deal with the response. The end function on the response object sends whatever text is passed to it and tells the server that the response is done.
  • In the next code line, varserver=http.createServer(serverResponse);, we are actually creating a web server by invoking the createServer function on the HTTP object we required earlier. We pass the serverResponse function to the createServer function, which becomes a callback function for the server. We will store a reference to the server we just created in the variable called server.
  • In the last line of the code, server.listen(3000);, we will invoke the listen function on the server object we just created. We will pass to it an integer representing the port number we want it to use to listen to requests. This bit of code actually starts up the server, and has it listen to requests on port 3000.

Setting up a Node.js project with NPM

As Node.js projects become larger, having a tool to mange it properly is important. Concerns such as consistent dependency management, version management, and environment management are made easier using Node Package Manager and the package.json file.

Fortunately, the smart people who created Node.js created a method of doing that using NPM. Running npm init from the command line will set up a Node.js project and build out a package.json file, which is used to manage your node projects. Let's try it with your hello Node project. Note that some of the prompts are optional and can be left blank, as shown in the following commands:

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (SPA-js) hello-node
version: (1.0.0) 
description: my new program
entry point: (hello.js) 
test command: 
git repository: 
keywords: 
author: Your Name
license: (ISC) 
About to write to /Users/your-home/helloNode/package.json:
{
  "name": "hello-node",
  "version": "1.0.0",
  "description": "my new program",
  "main": "hello.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "John Moore",
  "license": "ISC"
}
Is this ok? (yes) 

Pressing Enter at this point will create the package.json file in the directory you're in. Open it in your IDE or text editor and take a look. While you're in there, let's make the following small change to the scripts section:

"scripts": { 
  "test": "echo "Error: no test specified" && exit 1", 
  "start": "node hello" 
} 

The scripts section of package.json allows you to run code using NPM. In this case, typing npm start will run the node hello command and start your web server. It's not a super efficient shortcut at this point, but you can create efficient and useful aliases for lots of commands this way.

One of the very important things that NPM does is manage dependencies. In the next section, on Express, you'll see how to store references to NPM modules and their versions in the package.json file. This is important when working as part of a group or team. By taking a copy of a project's package.json file, a developer can recreate the environment for the project just by running NPM installation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.163.250