Learning Node.js for Mobile Application Development - Stefan Buttigieg - E-Book

Learning Node.js for Mobile Application Development E-Book

Stefan Buttigieg

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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, which means that developers can use the same language to write backend code. Also, it’s increasingly being seen as a modern replacement for PHP in web development, which relies on fast-paced data exchange. The growing community and the large amount of available modules makes Node.js one of the most attractive development environments.
This book takes a step-wise and incremental approach toward developing cross-platform mobile technologies using existing web technologies. This will allow you to truly understand and become proficient in developing cross-platform mobile applications with Node.js, Ionic Framework, and MongoDB.
The book starts off by introducing all the necessary requirements and knowledge to build a mobile application with a companion web service. It covers the ability to create an API from scratch and implement a comprehensive user database that will give you the opportunity to offer a mobile application with a personalized experience.
Midway through the book, you will learn the basic processes to create a successful mobile application. You will also gain higher-level knowledge, allowing you to develop a functional and secure mobile application to ensure a seamless user experience for end users.
Finally, the book ends with more advanced projects, which will bring together all the knowledge and expertise developed in the previous chapters to create a practical and functional mobile-application that has useful real-world features.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 244

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Node.js for Mobile Application Development
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Setting Up Your Workspace
The Node.js backend
Installing Node.js on different systems
Windows
Linux
Ubuntu/Debian
Fedora/RHEL/CentOS
Verifying your installation
Mac OS X
Verifying your installation
Setting up the Ionic framework and Cordova for Mac OS X
Setting up the Ionic framework and Cordova for Windows
Setting up the platform dependencies
Installing Java
Setting up Android Studio for Android, Mac, and Windows
Setting up the Android Software Development Kit
Setting up your physical Android device for development
Enabling Developer options
Enabling USB debugging
Trusting a computer with installed IDE using secure USB debugging (devices with Android 4.4.2)
Setting up the Environment Variables on Windows 7 and higher
Setting up the Environment Variables for iOS on Mac OS X
Installing the iOS SDK
MongoDB
Installation of MongoDB on different Operating System
Windows
Linux
Ubuntu
Fedora/RHEL/CentOS
Starting MongoDB
Mac OS X
Connecting to MongoDB
Windows
Linux and OS X
Summary
2. Configuring Persistence with MongoDB
Learning outcomes of MongoDB
An introduction to MongoDB
Documents
Collections
Databases
An example – a product order database
Connecting to MongoDB
Linux and Mac OS X
Windows
Creating a database
Creating our collections
Creating relations between documents
Querying MongoDB
Searching by ID
Searching by property value
Advanced queries
Connecting MongoDB and Node.js
Setting up a basic project
Connecting to MongoDB
Summary
3. Creating an API
Learning outcomes of the RESTful API
RESTing easy
It's all hypermedia
GET
GET all
GET by ID
POST
PUT
DELETE
Building a RESTful API with Node.js
Setting up the RESTful API
The HTTP module
Dissecting the HTTP server
Returning JSON
Implementing our GET handlers
Implementing a router
Implementing our POST handlers
Implementing the DELETE and PUT handlers
Testing the API
Moving forward
Summary
4. Securing Your Backend
Understanding the outcomes of token-based authentication
The theoretical bit
A small token of trust
Playing your role
Putting it all together
Implementation
Adding the new collections
Adding an authentication module
Creating functions to register and help users log in
Registering users
Enabling users to log in
Extending our API
OAuth
Time-stamped access tokens
Hashing passwords
Summary
5. Real-Time Data and WebSockets
Polling
WebSockets
Using WebSockets in Node.js
Setting up our project
Installing socket.io
Creating a chat interface
A basic file server
An alternate chat
The efficient serving of static files
Summary
6. Introducing Ionic
Setting up your Ionic web account
Creating your first Ionic application
Checking out your Ionic applications with Ionic View
Installing Ionic View on Android
Installing Ionic View on iOS
Testing your application on the iOS Ionic View App
Testing your application on Android
Sharing your application with collaborators
Going further
Summary
7. Building User Interfaces
The structure of an Ionic project
Introducing AngularJS
The structure of an Angular app
Modules
Modules within modules within modules
Services, controllers, and other beasts
The Angular MVC pattern
The view
The controller
The model
Putting it all together
Modifying an Ionic project
Modifying the header
Modifying the tab colour, icons, and names
Modifying our pages
Adding a new tab
Creating a new controller
Creating a view
Adding a state for the new tab
Testing the newly created tab
Going further
Summary
8. Making Our App Interactive
Creating a new project
Creating a basic MVC project
Creating the view
Creating the list view
Creating the controller
Connecting the view and controller
Testing the connection
Creating the model
Services
Creating services
Creating a factory
Accessing the device data
Accessing native services
ngCordova
Adding Cordova contacts to our factory
Building for native devices
Android
Emulator
A physical device
The list view revisited
Summary
9. Accessing Native Phone Features
Creating the project
Creating the basic app structure
Integrating Google Maps into the app
Angular directives
Creating directives
Restricting directives
Scope isolation
DOM manipulation
Putting it all together
Adding geolocation via GPS
Summary
10. Working with APIs
Setting up Parse
Setting up the Ionic project
Connecting Parse to our project
Defining app states
Creating controllers and templates
Testing our application
Summary
11. Working with Security
An overview of client-side security
Client-side security is a convenience
The basic components of client-side security
Building a secure app
Starting off
A basic authentication service
The login function
The isAuthenticated function
The getCurrent function
Implementing route authentication
Summary
12. Working with Real-Time Data
A refresher – WebSockets
Getting the lay of the land
What we will need
Creating the server
Building the chat app
Setting up the basic app structure
The input section
The message view
The ChatService function
Adding WebSockets to the mix
Updating the chat view
Going further
Summary
13. Building an Advanced Chat App
We need some room!
Namespaces
Creating a multiroom chat application
Configuring the basic layout
Building the server
Summary
14. Creating an E-Commerce Application Using the Ionic Framework
Designing our application
Creating an Ionic project
Implementing our designs
Setting up the product API
Connecting the product API to our Ionic app
Summary
Index

Learning Node.js for Mobile Application Development

Learning Node.js for Mobile Application Development

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book 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 book to ensure the accuracy of the information presented. However, the information contained in this book 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 book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2015

Production reference: 1231015

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-049-8

www.packtpub.com

Credits

Authors

Stefan Buttigieg

Milorad Jevdjenic

Reviewers

Danny Allen

Alex (Shurf) Frenkel

Siddique Hameed

Prasanna Ramanujam

Commissioning Editor

Nadeem N. Bagban

Acquisition Editor

Harsha Bharwani

Content Development Editor

Sumeet Sawant

Technical Editor

Tejaswita Karvir

Copy Editor

Vedangi Narvekar

Project Coordinator

Shweta H Birwatkar

Proofreader

Safis Editing

Indexer

Hemangini Bari

Graphics

Abhinash Sahu

Production Coordinator

Komal Ramchandani

Cover Work

Komal Ramchandani

About the Authors

Stefan Buttigieg is a medical doctor, mobile developer, and entrepreneur. He graduated as a doctor of medicine and surgery from the University of Malta. He is currently enrolled at the University of Sheffield, where he is pursuing a master's degree in health informatics. He has more than 5 years of experience working in international medical students' organizations, where he occupied various technical positions. He founded MD Geeks, an online community that brings together health professionals, developers, and entrepreneurs from around the world to share their passion for the intersection of healthcare and information technology. He is mostly interested in mobile development, especially for the Android and iOS platforms, open source healthcare projects, user interface design, mobile user experience, and project management.

Milorad Jevdjenic is a programmer, open source enthusiast, and entrepreneur. He studied computer science at the University of Gothenburg with a focus on formal verification methods. Currently, he works as a software developer in the medical sector and also does independent commercial and pro bono consulting. Milorad is passionate about technology. He looks upon open source, and open standards in particular, as the fundamental drivers that are needed to build better societies. When he is not on the computer tinkering with code, he enjoys hiking, sports, and fine whiskey.

About the Reviewers

Danny Allen is a full stack web developer with a focus on user experience design and implementation. He is a founder and director of the international consultancy, Wonderscore Ltd.

Skilled across a wide range of backend and frontend technologies, including Python and Django, JavaScript, AngularJS, Node.js, HTML5, and CSS3, his recent work has involved e-learning and government projects in the United Kingdom.

Danny currently lives and works in Barcelona, Spain.

His portfolio and contact details can be found at http://dannya.com.

Alex (Shurf) Frenkel has been working in the field of web application development since 1998 (the beginning of PHP 3.x). He has an extensive experience in system analysis and project management. Alex is a PHP 5.3 Zend Certified Engineer (ZCE) and is considered to be one of the most prominent LAMP developers in Israel. He is also a food blogger. You can view his blog by visiting http://www.foodstuff.guru.

In the past, Alex was the CTO of ReutNet, one of the leading Israeli web technology -based companies. He also worked as the CEO/CTO of OpenIview LTD, a company built around the innovative idea of breaching the IBM Mainframe business with PHP applications, and as a CTO and chief architect of a start-up named GBooking. He also provided expert consulting services to different companies regarding various aspects of web-related technology.

Frenkel-Online is a project-based company that works with a number of professional freelance consultants in Israel and abroad. Currently, their permanent staff comprises several professionals from Israel and abroad for the company's PHP projects, and a changing number of specialists in other programming languages for the rest of the projects.

FoodStuff.Guru is a pet project that brings not only high-style food, but also common food, to the web so that it can be reviewed by people for the people. The blog is multilingual and can be viewed by visiting http://www.foodstuff.guru.

Siddique Hameed is currently working as a full-stack engineer on Simplify Commerce (http://simplify.com), a payment gateway platform from MasterCard. In his diverse career experience, he has crafted software for Fortune 500 companies as well as startups with industry domains ranging from commerce, social media, telecom, bio-informatics, finance, publishing, insurance, and so on.

He is a passionate technologist who actively contributes to open source projects. He speaks frequently at tech events and meet-ups and mentors the participants of hackathons and code boot camps.

His current focus areas include AngularJS, Ionic, Node.js, HTML5, CSS3, Cloud computing, mobile applications, and the Internet of Things (IoT). In his spare time, he likes to tinker with the Raspberry Pi and build DIY gadgets.

I dedicate this to my mom, dad, my beloved wife, Farzana, and my wonderful daughters, Fareeha and Sameeha!

Prasanna Ramanujam is a software engineer. He has a master's degree in software engineering. He is a full-stack developer, and he has been a Node.js developer since the release of Node.js version 0.2. He has helped architect and scale the Node.js application at companies in Silicon Valley. He has also published many private and public NPM modules.

He is passionate about building high-availability systems. He likes to work on asynchronous programming, distributed computing, and NoSQL databases. He also likes music, skiing, and water sports. He can be found on Twitter at @prasanna_sr.

I would like to thank my family members and friends for supporting me.

Also, my sincere thanks to Pooja Mhapsekar and the other members from Packt Publishing for giving me this opportunity as well as Shweta Birwatkar for coordinating with me throughout the journey.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

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.

What this book covers

Chapter 1, Setting Up Your Workspace, explains how to set up your work environment to develop cross-platform applications by using the Ionic framework as the frontend tool, Node.js for the backend, and the integrated development environment, Atom.

Chapter 2, Configuring Persistence with MongoDB, goes through the necessary configurations that are needed to make an instance of MongoDB work with Node.js. You will learn how to set up security and a database, install the relevant MongoDB driver for Node.js, and communicate with the database from a Node.js instance.

Chapter 3, Creating an API, looks at how we can set up a uniform interface for sending and receiving data and basic functionality on the Node.js server by building an API (Application Programming Interface) that exposes it. We will cover the basic REST topics and show you how to configure routes to perform simple read/write operations on our data.

Chapter 4, Securing Your Backend, shows that this type of remedies can be achieved by building a basic security mechanism in order to control user access. Specifically, we will deal with token-based authentication and show you how this makes it easy to limit access to your backend. In doing so, we will introduce the concept of roles and how they figure in our authentication scheme.

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.

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.

What you need for this book

You'll need the following software:

Android StudioAndroid Software Development KitThe Ionic frameworkMongoDBAtomXCode

Who this book is for

This book is intended for web developers of all levels of expertise who want to deep dive into cross-platform mobile application development without going through the pain of understanding the languages and native frameworks that form an integral part of developing for different mobile platforms.

This book is also for developers who want to capitalize on the Mobile First strategy and who are going to use JavaScript for their complete stack.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via 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 on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, 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 all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Downloading the color images of this book

We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from: http://www.packtpub.com/sites/default/files/downloads/1453OT_ColorImages.pdf.

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 books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Setting Up Your Workspace

The overarching goal of this book is to give you the tools and know-how needed to efficiently construct modern, cross-platform solutions for your users. In this chapter, we will focus on the tools themselves, showing you how to bootstrap your development environment to tackle the challenges that we have in store for you in the remainder of the book. We will also give you a brief introduction to each tool in order to give you an idea about why they fit into your toolchain. If any such detail seems unclear at this point, do not worry. We will delve into everything you need to know about each tool in the relevant parts of the book.

After reading this chapter, you will know how to install, configure, and use the fundamental software components that we will use throughout this book. You will also have a good understanding of why these tools are appropriate for the development of modern apps.

The Node.js backend

Modern apps have several requirements, which cannot be provided by the app itself, such as central data storage, communication routing, and user management. In order to provide such services, apps rely on an external software component known as the backend. The backend will be executed on one or more remote servers, listen to network requests from the devices that run the app, and provide them with the services that requests require.

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.

Installing Node.js on different systems

Node.js is delivered as a set of JavaScript libraries, executing on a C/C++ runtime built around the Google V8 JavaScript Engine. The two come bundled together for most major operating systems (OS), and we will look at the specifics of installing it in the following sections.

Note

Google V8 JavaScript Engine is the same JavaScript engine that is used in the Chrome browser, which is built for speed and efficiency.

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.

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.

Verifying your installation

Now that we have finished the install, let's do a sanity check and make sure that everything works as expected. To do so, we can use the Node.js shell, which is an interactive runtime environment for the execution of JavaScript code. To open it, first open a terminal, and then issue the following to it:

node

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!

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.

Verifying your installation

After the install finishes, open a terminal and start the Node.js shell by issuing the following command:

node

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!");

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!

Setting up the Ionic framework and Cordova for Mac OS X

After installing Node.js on your Mac, proceed to open your command-line application and input the following command:

$ sudonpm install -g ionic

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

The preceding command line should result in the following output:

Installing Cordova on OS X is very similar to installing Ionic. You can run the following command to install Cordova:

$ sudonpm install -g cordova

Setting up the Ionic framework and Cordova for Windows