Learning Node - Js For Mobile Application Development - Sample Chapter
Learning Node - Js For Mobile Application Development - Sample Chapter
$ 44.99 US
28.99 UK
P U B L I S H I N G
Stefan Buttigieg
Milorad Jevdjenic
ee
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Sa
m
Stefan Buttigieg
Milorad Jevdjenic
Preface
Node.js is a massively popular JavaScript library that lets you use JavaScript to
easily program scalable network applications and web services. People approaching
Node.js for the first time are often attracted by its efficiency, scalability, and the fact
that it's based on JavaScript, the language of the Web. This means that developers can
use the same language to write backend code. Also, it's increasingly being looked upon
as a modern replacement for PHP in web development, which relies on fast-paced data
exchange. This growing community and the large amount of available modules makes
Node.js one of the most attractive development environments.
Preface
Chapter 5, Real-Time Data and WebSockets, shows you how to enable real-time
data communication using WebSockets. This will allow your server to directly
communicate with connected clients without having to perform polling on
the client side.
Chapter 6, Introducing Ionic, covers all the basic essentials that are needed to set up a
working environment, which is required to efficiently create and share Ionic apps.
Chapter 7, Building User Interfaces, takes the template project that we created in the
past few chapters and modifies it to something closer to what we envisioned by
altering the appearance of the user interface. In addition to this, we will also start
experimenting with the Ionic project code to deeply understand what the project
is made up of.
Chapter 8, Making Our App Interactive, covers a lot of ground, going into the details
of AngularJS and learning more about the interaction of the model, view, and
controller. We will also see how to use the Cordova plugins and ngCordova in
order to access native features. Finally, we will also have a look at how to create
services and use them in order to serve data to the users.
Chapter 9, Accessing Native Phone Features, discusses how to directly work with the
Google Maps API in order to render and work with maps.
Chapter 10, Working with APIs, explores how to access external APIs in order to
send and retrieve data. You will learn how to encode/decode data to/from JSON
in our app in order to provide a standard interface for processing.
Chapter 11, Working with Security, introduces the concept of security in mobile
apps in the context of authenticating and authorizing local users. We will have a
look at how to implement a common login feature, which contacts a remote server
(run by Node.js, of course!) in order to verify that a given pair of user credentials is
correct. We then use this information in order to grant the user access to the rest of
the application.
Chapter 12, Working with Real-Time Data, covers how to set up WebSocket
communication through the mobile app in order to subscribe to dynamic
notifications from a server. We will elaborate on how this helps us develop truly
dynamic applications, such as chat apps. This chapter will further introduce the
concept of push notifications, which will allow our app to get updates from a
server on a dynamic basis.
Preface
Chapter 13, Building an Advanced Chat App, expands this mobile app and makes it
more advanced by adding the features of chat rooms and notifications. In doing
so, we will demonstrate how the concept of namespacing works on socket.io,
which is one of the most important aspects of this library.
Chapter 14, Creating an E-Commerce Application Using the Ionic Framework, brings
together the knowledge that you have accumulated from this book and implements
it in an easy-to-use Ionic framework that can be used in your very own projects.
[1]
The backend that we will use in this book is Node.js, a powerful but strange beast
in its category. Node.js, at the time of writing this book, is the only major backend
that is written almost entirely in JavaScript, which in reality is a frontend scripting
language. The creators of Node.js wanted a backend that could be integrated with
the apps written in JavaScript as seamlessly as possible, and you cannot get much
closer to that than Node.js. Beyond this, Node.js is known for being both reliable
and high-performing.
In terms of architecture, Node.js is highly modularized and designed from the
ground up to be extendable through plugins or packages. Node.js comes with its
own package management system, Node Package Manager (NPM), through which
you can easily install, remove, and manage packages for your project. You will see
how to use NPM in order to install other necessary components later in this chapter.
Windows
For Windows, there is a dedicated MSI wizard to install Node.js, which can be
downloaded from the project's official website. To do so, go to the main page,
navigate to Downloads, and then select Windows Installer. After it has downloaded,
run the MSI wizard, follow the steps to select the installation options, and conclude
the install. Keep in mind that you will need to restart your system in order to make
the changes effective.
[2]
Chapter 1
Linux
Most major Linux distributions provide convenient installs of Node.js through their
own package management systems. However, it is important to keep in mind that
for many of them, Node Package Manager (NPM) will not come bundled with the
main Node.js package. Rather, it is provided as a separate package. We will show
how to install both in the following section.
Ubuntu/Debian
Open a terminal and issue sudo apt-get update to make sure that you have the
latest package listings. After this, issue apt-get install nodejsnpm in order to
install both Node.js and NPM in one swoop.
Fedora/RHEL/CentOS
On Fedora 18 or later, open a terminal and issue sudo yum install nodejsnpm.
The system will do the full setup for you.
If you are running RHEL or CentOS, you need to enable the optional EPEL
repository. This can be done in conjunction with the install process, so that you
do not need to do it again while upgrading the repository, by issuing the
sudo yum install nodejsnpm --enablerepo=epel command.
This will start the interpreter, which will appear as a shell, with the input line
starting with the > sign. Once you are in it, type the following:
console.log("Hello world!);
Then press Enter. The Hello world! phrase should appear on the next line.
Congratulations, your system is now set up for the running of Node.js!
[3]
Mac OS X
For OS X, you can find a ready-to-install PKG file by going to www.nodejs.org,
navigating to Downloads, and selecting the Mac OS X Installer option. Otherwise,
you can click on Install, and your package file will automatically be downloaded:
Once you have downloaded the file, run it and follow the instructions on the screen.
It is recommended that you keep all the default settings offered unless there are
compelling reasons for you to change something with regard to your specific machine.
This will start the interactive node shell, where you can execute JavaScript code.
To make sure that everything works, try issuing the following command to
the interpreter:
console.log("hello world!");
[4]
Chapter 1
After pressing the Enter key, the hello world! phrase will appear on your screen.
Congratulations, Node.js is all set up and good to go!
After inputting this command, you will be prompted to input your password as
shown in the following screenshot:
If you have already set up the permissions for npm on OS X, you can install Ionic with
the following command:
$ npm install -g ionic
[5]
Installing Cordova on OS X is very similar to installing Ionic. You can run the
following command to install Cordova:
$ sudonpm install -g cordova
Once you have ensured that you have successfully installed npm, you can go ahead
and run the following command:
npm install -g ionic
[6]
Chapter 1
This step should result in an output, which shows that you have successfully
installed Ionic.
In order to install Cordova, you can also use npm and run the following command:
npm install -g cordova
Once you receive a successful output, you can go ahead and start setting up the
platform dependencies.
An experimental setup for Windows:
In Windows, you will have the opportunity to set up a Vagrant
package, which is a one-stop-shop for the installation of Ionic on your
Windows machine. This is accessible at https://github.com/
driftyco/ionic-box.
Installing Java
If you do not have Java installed or if your version is below 6.0, install the Java
JDK by heading over to http://j.mp/javadevkit-download, a customized and
shortened link, and choosing the version that applies to you.
The main recommendation for these projects is that you install a version of JDK
6.0 or higher.
Select the JDK for your OS. On an Intel-based Mac, you can use the following useful
table to check whether your Mac is a 32- or 64-bit OS.
You can check for Processor Name by clicking on the Apple logo in the top-left
corner of your screen, followed by About my Mac:
Processor Name
32- or 64-bit
32 bit
32 bit
64 bit
64 bit
64 bit
[7]
Processor Name
32- or 64-bit
64 bit
Core i3
64 bit
Core i5
64 bit
Core i7
64 bit
In the case of Windows, if you have a machine that was purchased in the last few
years, you should go for the x64 (64-bit) version.
[8]
Chapter 1
3. Accept the terms and conditions of the Software Use Agreement and
click on Download:
4. For Mac, double-click on the downloaded file, follow the prompts, and then
drag the Android Studio icon into your Applications folder:
[9]
5. For Windows, open the downloaded file, and then go through the Android
Studio Setup Wizard to complete the install.
[ 10 ]
Chapter 1
This is what the SDK Manager looks like. If you need to install a package, you need
to check the mark of that particular package, click on Install packages, and then
finally accept the licenses:
[ 12 ]
Chapter 1
From the App Store, search for Xcode in the App Store application
Command-line tools are integrated within Xcode. Previously, this was installed
separately. Once you've downloaded and installed Xcode, you are prepared to
handle iOS projects from a machine that has Mac OS X enabled.
MongoDB
In order to store data related to your app and users, your server will need a
databasea piece of software that is dedicated solely to data storage and retrieval.
Databases come in many variants. In this book, our focus is NoSQL databases,
which are so named because they don't use the traditional table-oriented SQL
data access architecture that is used by the more well-known relational databases,
such as Oracle, MySQL, and PostgreSQL. NoSQL databases are very novel in their
design and features and excellent for the tackling of the challenges that one may
face in modern app development.
The NoSQL database that we will use throughout this book is MongoDB (it is often
abbreviated as MDB or simply Mongo). MongoDB is a document-oriented database
that which stores data in documents, which are data structures that are almost
identical to the standard JSON format.
Let's have a look at how to install and get MongoDB running. If you have used a
more traditional DB system, you may be surprised at how easy it is.
[ 13 ]
Windows
MongoDB ships with a complete MSI for installation on Windows systems. To
download it, go to the project's official website, www.mongodb.org, navigate to
Downloads, and select the Windows tab. You will be offered the following three
choices to download:
Windows 64-bit R2+: Use this if you are running Windows Server 2008,
Windows 7 64-bit, or a newer version of Windows
Windows 32-bit: Use this if you have a 32-bit Windows installation that is
newer than Windows Vista
Windows 64-bit legacy: Use this if you are using Windows Vista 64-bit,
Windows Server 2003, or Windows Server 2008.
MongoDB does not run on Windows XP at all.
After you have downloaded the MSI, run it with administrator privileges in order
to perform the installation. The installation wizard will give you a default location
where MongoDB will be installedC:/mongodb/. You can change this if you desire,
but it is recommended that you keep it as we will assume that this is the location
where MongoDB resides for the remainder of the book.
After the installation has finished, the next step is to configure a data directory
where MongoDB can store the data that we will feed it with. The default location
for this directory is /data/db. We will need to make sure that this directory exists
and is writeable before we start our MongoDB instance for the first time. So, fire
up the command prompt with administrator privileges and issue the md/data/
dbcommand. After doing so, we are good to start the database server itself. To do
so, stay in the command prompt and issue the following command:
C:/mongodb/bin/mongodb.exe
You should receive a confirmation that MongoDB is now running and listening for
connections. All is set!
[ 14 ]
Chapter 1
Linux
On Linux, you will find MongoDB ready-packaged on most major distributions.
However, we strongly recommend that you use the project's own repositories in
order to make sure that you always have access to the most current security and
stability updates.
Ubuntu
First off, you will need to enable the official MongoDB repository. To do so, open
a terminal and first import the project's public GNU Privacy Guard (GPG) key
as follows:
sudo apt-key adv --keyserverhkp://keyserver.ubuntu.com:80
--recv7F0CEB10
Once this is done, create a listing for the repository itself by issuing the following
command:
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart
dist10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Your repository listing is now active. Let's make Advanced Package Tool (APT)
aware of it in order to install MongoDB, as follows:
sudo apt-get update
Fedora/RHEL/CentOS
Our first order of business here is to enable the official MongoDB repository.
To do so, first make sure that you have the nano text editor installed by opening
a terminal and issuing the following command:
sudo yum install nano
After this is done, add the repository by issuing the following command:
sudonano /etc/yum.repos.d/mongodb.repo
[ 15 ]
Nano will open a new, blank text file. Copy and paste the following into the file:
[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1
Save and close the file by pressing Ctrl+O, followed by the Enter key. This is followed
by Ctrl+X.
Finally, carry out the installation by issuing the following command:
sudo yum install mongodb-org
Starting MongoDB
After the installation of MongoDB, you will need to start MongoDB as a service in
order to get it running. To do so (on all the distros that were previously mentioned),
open a terminal and run the following command:
sudo service mongodb start
It is important that if you have SELinux running, you must make sure that it allows
MongoDB to access its default port. To do so, issue the following before you issue
the preceding command:
sudosemanage port -a -t mongod_port_t -p tcp 27017
Mac OS X
The easiest way to both install and stay up to date with MongoDB on OS X is by
using the Homebrew package manager. Even if we just use it to install MongoDB
here, you will most likely find it useful later for the installation of other software
packages that you may need for your own projects after you finish this book.
Installing Homebrew is simple; just open a terminal and issue the following command:
ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)"
When this finishes, make sure that the Homebrew package database is up to date,
as follows:
brew update
[ 16 ]
Chapter 1
When the install has finished, we will need to define a data directory in order to give a
location for MongoDB to store its data. By default, this directory will be at /data/db.
So, unless you specify something else, you will need to make sure that this directory
exists and is both writeable and readable by the user running your MongoDB instance.
For example, if the user running MongoDB on your system is john, you will have to
issue the following commands:
sudomkdir -p /data/db
sudochmod 0755 /data/db
sudochownmongod:mongod /data/db
Now that this is done, it is time to start up MongoDB. To do so, make sure that you
are logged in as john, open a terminal, and simply issue the following command:
mongodb
That's it! You should receive a notification that MongoDB has started and is listening
for a connection. Your instance is ready to go!
Connecting to MongoDB
In order to read and write from the MongoDB instance, we will first need to connect
to it. In fact, MongoDB acts as a server in its own right. It exposes its functionality
via a network port on which clients can then connect either through the local
machine, or even over the Internet.
Since this functionality is disabled by default due to it being a
shoddy security practice, it will require a special configuration
of the operating system that MongoDB is running on. We will
not discuss this functionality as it falls outside the scope of this
book, but we will refer to the MongoDB documentation for
several helpful examples of how to achieve it for a variety of OS.
To connect to a MongoDB instance, you will need at least the following information:
[ 17 ]
The database that you are trying to connect to: Don't confuse this with the
MongoDB instance itself. Each MongoDB instance can contain any number
of databases, with each belonging to different users. The instance simply
manages access to them.
A username and its associated password to grant you access to the instance
and any databases therein that you are authorized to interact with.
A very easy way to try out this connectivity yourself and verify that MongoDB
works as expected is by using the MongoDB shell, a tool that comes installed with
MongoDB itself using the methods that we have described previously. How you
access the shell varies depending on your OS. I will show each method in the
following section and then give an example of how to use the shell itself since
this will be the same on all platforms.
Windows
First, make sure that MongoDB is running by following the process that was outlined
previously. After this, issue the following command in your command prompt:
C:\mongodb\bin\mongo.exe
Linux and OS X
First, make sure that MongoDB is running. Then, open a terminal and issue the
following command:
mongo
Now that our shell is running, let's verify that everything works by creating a
database and adding some data to it.
To create a database, issue the following command to the shell:
use Fruits
This will create a database named Fruits, to which we can immediately start
adding data. (What, you were expecting more overhead? Not in MongoDB!)
[ 18 ]
Chapter 1
The shell should respond with the { "ok" : 1 } JSON response that tells us that
everything went well. Now, let's add some chewy fruits to our collection, as follows:
db.Chewy.insert({"name" : "pear"});
db.Chewy.insert({"name" : "apple"});
Even if the naming makes it intuitively clear what is going on in the preceding
code, don't worry if you do not understand all the details yet. We will get to this
in due course.
Finally, let's make MongoDB show us the chewy fruits that we stored. Issue the
following command:
db.Chewy.find();
The _id numbers will be different on your system, but you will find that the names
are the same. All the fruits are where we want them to be.
Congratulations, you now have a fully working MongoDB setup ready for action!
Summary
By now, you may have perhaps noted the red thread running through all the
components that we picked for our toolchain; they are all based on JavaScript. This
gives us the ability to write all our logic from top to bottom in one single language
rather than using different ones for different components (Objective-C or Java for the
client, PHP for the server, SQL for the database, or some other unholy combination).
As you will see throughout the remainder of the book, this will make it much easier
for us to write concise, focused, and comprehensible code.
[ 19 ]
Once you go through all the preceding steps, I can safely assume that you have the
necessary toolkit and you are ready to tackle the upcoming chapters, where we will
have an opportunity to create our very first Ionic app and make it work on both
Android and iOS devices.
Once you finish setting up your workspace, I recommend that you spend some
time reading the Apache Cordova documentation, especially the documentation
related to the different platform dependencies.
In the next chapter, we will perform further preparations and configure persistence
with MongoDB as part of our preparations for our very own backend for our
Ionic app.
[ 20 ]
www.PacktPub.com
Stay Connected: