All rights reserved. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights & Permissions Department, please visit www.pearson.com/permissions.
No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.
ISBN-13: 978-0-13-806540-9
ISBN-10: 0-13-806540-3
Library of Congress Control Number: 2023935868 ScoutAutomatedPrintCode
TRADEMARKS
Microsoft and the trademarks listed at http://www.microsoft.com on the “Trademarks” webpage are trademarks of the Microsoft group of companies. All other marks are property of their respective owners.
WARNING AND DISCLAIMER
Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author, the publisher, and Microsoft Corporation shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the programs accompanying it.
SPECIAL SALES
For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or (800) 382-3419.
For government sales inquiries, please contact governmentsales@pearsoned.com.
For questions about sales outside the U.S., please contact intlcs@pearson.com.
Editor-in-Chief
Brett Bartow
Executive Editor
Loretta Yates
Development Editor
Rick Kughen
Managing Editor
Sandra Schroeder
Senior Project Editor
Tracey Croom
Project Editor
Charlotte Kughen
Copy Editor
Rick Kughen
Indexer
Cheryl Lenser
Proofreader
Charlotte Kughen
Technical Editor
John Ray
Editorial Assistant
Cindy Teeters
Cover Designer
Twist Creative, Seattle
Compositor
Bronkella Publishing, LLC
Graphics
TJ Graham Art
Credits
Cover: 32 pixels/Shutterstock, Chapter 04, Screenshot of OpenJS website: OpenJS Foundation
Chapters 7 and 11: Screenshots of MongoDB UI: MongoDB, Inc.
Chapter 11: Screenshots of JWT.io UI: Okta, Inc.
Chapter 12: Screenshots of Raspberry Pi UI: Raspberry Pi Ltd; screenshots of HiveMQ website: HiveMQ GmbH; screenshots of Connected Little Boxes website: Connected Humber CIC
About the author
Rob Miles spent more than 30 years teaching programming at the University of Hull in the United Kingdom. He’s a Microsoft MVP with a passion for programming and creating new things. He runs a tiny company promoting the use of software and devices in the community and loves building things and putting code into them. He reckons that programming is the most creative thing you can learn how to do. He claims to know a lot of really good jokes, but nobody has ever heard him tell one.
If you want an insight into the Wacky World™ of Rob Miles, you can read his blog at www.robmiles.comand follow him on Twitter as @RobMiles.
Contents at a glance
Part 1: The cloud
Chapter 1 Code and the cloud
Chapter 2 Get into the cloud
Chapter 3 Make an active site
Chapter 4 Host a website
Part 2: Make a cloud-based application
Chapter 5 Build a shared application
Chapter 6 Create a shared experience
Chapter 7 Design an application
Chapter 8 Build an application
Chapter 9 Turn professional
Part 3: Building with Cloud Technologies
Chapter 10 Store data
Chapter 11 Activity tracking and sessions
Chapter 12 JavaScript technologies Index
Contents
Introduction
Part 1: The cloud
1 Code and the cloud
What is the cloud?
The World Wide Web
Putting the web in the cloud
JavaScript
JavaScript heroes: functions
The JavaScript function object
Lifting the lid on JavaScript
References to JavaScript function objects
Function expressions
Function references as function arguments
Returning values from function calls
Returning multiple values from a function call
Make a console clock
Getting the date and time
Arrow functions
What you have learned
2 Get into the cloud
Working in the cloud
Storing Git repositories
GitHub and open-source software
Get Visual Studio code
How a web page works
Loading a page and displaying it
Make an active web page
Interact with the document object
Web pages and events
Making a time travel clock
Add buttons to a page
Share values with global variables
Host a website on GitHub
What you have learned
3 Make an active site
Get input from a user
The HTML input element
Input types
Storing data on the local machine
JavaScript heroes: let, var, and const
Making page elements from JavaScript
Cheese Finder
What you have learned
4 Host a website
Node.js
JavaScript heroes: modules
Create a module and require it
require and import
Using import in the browser
The dark side of imported code
Make a web server
Serving from software
Serving out files
Active sites
What you have learned
Part 2: Make a cloud-based application
5 Build a shared application
Upgrade Cheese Finder
Adding some color
Add a game ending
Add randomness
Add more cheese
Even more cheese
Create a shared game
Design a protocol for a conversation
Create endpoints
Start the game
The game server
Play the game
What you have learned
6 Create a shared experience
Sharing gameplay
Create shared gameplay
Debug shared gameplay
Make pseudo-random values
Create a pseudo-random library
Generate timed randomness
Use worldwide time
Prepare for the cloud
Optimize performance
Avoid recalculations
Improve structure
Buy a domain name
Put your name on it
Deploy an application
What you have learned
7 Design an application
The Tiny Survey application
Ethics, privacy, and security
Application workflow
Index page
Enter options
Select option
Display results
Extra workflows
Application data storage
JavaScript hero: classes
Classes for Tiny Survey
The Option class
The Survey class
The Surveys class
What you have learned
8 Build an application
Put on the style with Bootstrap
Getting started with Express
Express and node package manager
Express routes
Manage versions with Git
Use gitignore
Use page templates with EJS
Get the example application
The index page
Post data from a form
Receive input from a post
Enter the survey options
The enteroptions page
Generate pages using an EJS template
Use named route parameters
Build a survey data object
Build a select option page
Record survey responses
Render the results
What you have learned
9 Turn professional
Modular code
Comments/documentation
Error checking
Testing
Logging
“Professional” coding
Store application status with cookies
Cookies in Tiny Survey
Cookie middleware
Use cookies in Tiny Survey
What you have learned
Part 3: Building with cloud technologies
10 Store data
File data storage
Synchronous file writing
Asynchronous file writing
JavaScript heroes: the Promise
JavaScript heroes: await and async
Using async in Tiny Survey
Handle file errors
Create error-handling middleware
Database storage
Start with MongoDB
Mongoose and schemas
The SurveyManagerDB class
Testing asynchronous code
Refactoring Tiny Survey
Create route files
Tiny Survey deployment
Manage environment variables
Code and deploy with the nodemon package
Create a README.md file
What you have learned
11
Activity tracking and sessions
User tracking
Create a Globally Unique Identifier (GUID)
User tracking ethics
Use activity diagrams to describe workflow
Cookie approval workflow
Create tracking middleware
Store survey creators
Recognize survey creators
Tiny Survey improvements
User sessions
Store user details
Register and login workflow
Register a user
Hashing passwords
The register route
User login
Access tokens
Create an access token
Authenticate tokens
Session renewal
Role-based security
Creating the admin user
What you have learned
12 JavaScript technologies
Make your own cloud
Installing node
Host an application
Use MongoDB on your server
Shut down the server
Running a server
Control hardware from a server
Browser-controlled light
Remote button
Use WebSockets to send values from a server
Make a WebSocket
Use MQTT
MQTT in a node.js application
Create an Internet of Things network
Create your own IoT devices
Manage devices using the Connected Little Boxes server
Create a game using Phazer
Serving static files from Express
Further development
Typescript
React
Electron
Graphql
Socket.io
ml5.js
Espruino
What you have learned
Introduction
The fundamentals of what a program does have not changed since the invention of the first computer more than 80 years ago. Programs still take data in, do something with it, and then send data out. However, how programs are created, deployed, and consumed has changed massively, from central mainframes to personal computers to the cloud.
The cloud takes your programs and gives them wings. The cloud enables you to turn your ideas into solutions that anyone in the world can use. This book gives you a handle on cloud development. It explains the evolution of the cloud, identifies its challenges, and sets you on the road to becoming an accomplished cloud developer. You will learn how to code for the cloud, how to use cloud technology on your local machine, where code and data can be hosted, and how applications are built from cooperating software components.
It won’t always be an easy journey. Things worth doing tend to involve effort, and learning how to code for the cloud is one of them. Not everything will make sense when you first see it. Cloud solutions may contain multiple moving parts, which must all fit together to work correctly. In addition, there are people out there who will make it their business to try to undermine, overload, break, or steal your work, so you need to be prepared for this. You will have to learn how the cloud enables both bad and good behaviors. However, if you stay the course, you’ll be rewarded with skills you can use to take your ideas and bring them to life across the world.
How this book fits together
I’ve organized this book into three parts. Each part builds on the previous one to turn you into a successful cloud developer.
Part 1: The cloud
We start by considering where the cloud came from and the drivers behind its development. Then we begin making applications using JavaScript, learning language features and application libraries as we go. By the end of this part, we’ll have built applications running in the browser and also created server code that can run in the cloud.
Part 2: Make a cloud-based application
First we investigate the HTML Document Object Model in the browser and use it to create a playable game. Then we deploy the game into the cloud for anyone in the world to access. Next we move on to make our game a shared user experience powered by connected code running in both browser and server. We finish with an application design and build exercise, starting with an idea and ending with a cloud-ready application.
Part 3: Building with cloud technologies
This part starts by introducing techniques and tools to improve the quality of your applications. Then we move on to consider how to store application data in files and database documents. Next we discover how to create logins and implement role-based security for
users of an application. Finally we take a look at a host of exciting JavaScript-powered technologies, including creating your own servers to build your own personal cloud, connecting hardware lights and buttons to servers, linking applications to Internet Of Things devices, and making a fast-moving sprite-based game.
Online glossary
To help you learn the basic terminology of cloud application programming, I’ve created an expansive glossary. It contains definitions of terms you might not have seen before, or have seen in a different context. You can find the glossary at https://begintocodecloud.com/glossary.html.
How to use this text
A good way to use the text is to read through a section away from the computer, perhaps on the bus (unless you are driving it), and then go back and work through the examples and exercises when you are sitting next to a computer. This way, you can pick up on the theory and context without feeling forced to do anything with it, and then you can reinforce your understanding by applying it later. Each chapter starts by setting out what you will learn and finishes with questions that help you validate your understanding and give you thoughts to ponder.
Everything will be described in a strong context. You might not initially understand how something works, but you should understand the problem it is being used to solve. Eventually, you will start to see other contexts in which the tool or technique is used, at which point you can call yourself a proper developer.
The text is sprinkled with coding and debugging exercises to try, along with suggestions of how the examples can be applied and
extended. If you get stuck, you can watch a video walkthrough of the exercise.
Like learning to ride a bicycle, you’ll learn by doing. You must put in the time and practice to learn how to code. But this book will give you the knowledge and confidence to try your hand at programming, and it will also be around to help you if your programming doesn’t turn out as you expected. The following are some elements in the book that will help you learn by doing.
Make Something
Happen
Yes, the best way to learn things is by doing, so you’ll find Make Something Happen elements throughout the text. These elements offer ways for you to practice your programming skills. Each starts with an example and then introduces some steps you can try on your own. Everything you create will run on Windows, macOS, or Linux.
Also, each Make Something Happen includes a QR code like this one. Simply scan it with your mobile device to be taken to a video I’ve created, which takes you through the exercise. You can also see the video by visiting https://www.youtube.com/watch?v=LQJOm9zFfNk.
Code Analysis
A great way to learn how to program is by looking at code written by others and working out what it does (and sometimes why it doesn’t do what it should). You’ll find Code Analysis sections at regular intervals in the text. There are also a few debugging exercises that teach you how to view your code as it runs.
Programmer’s Points
I’ve spent a lot of time teaching programming. But I’ve also written many programs and sold a few to paying customers. I’ve learned some things the hard way that I really wish I’d known at the start. The aim of Programmer’s Points is to give you this information upfront so that you can start taking a professional view of software development as you learn how to do it.
Programmer’s Points cover a wide range of issues, from programming to people to philosophy. I strongly advise you to read and absorb these points carefully—they can save you a lot of time in the future!
Colorful code
You’ll already have noticed that the book is presented in bright colors, with eye-catching illustrations here and there. The code samples use color highlighting to help you navigate programs:
In JavaScript samples, code keywords (parts of the language) are blue, strings of text are red, and numeric values and comments are green
In HTML samples, elements and delimiters are brown, attribute names are red and attribute values are blue.
Delmiters are color matched. In other words, a blue open brace { will be matched with a corresponding blue close brace }, as green will be paired with green, brown with brown, and so on. This might not make a lot of sense right now, but it will really help you find your way around the sample code. The color schemes are based on ones used by the Visual Studio Code editor.
What you will need
You’ll need a computer and some software to work with the programs in this book. I’m afraid I can’t provide you with a computer, but in the first chapter, you’ll find out how you can get started with nothing more than a computer and a web browser. The book examples use the Edge browser, but you can use any browser
you like, such as Chrome, FireFox, or Safari. Later, you’ll discover how to use the Visual Studio Code development environment to create and debug JavaScript programs.
As you work through the book, you will create and use cloud services that will be hosted on systems in the cloud. You might think that this would be expensive, but all the example applications are based on technologies that are free for personal use. You will have to register for some of them, but they will not cost any money.
Using a PC or laptop
You can use Windows, macOS, or Linux to create and run the programs in the text. Your PC doesn’t have to be particularly powerful, but these are the minimum specifications I’d recommend: A 1 GHz or faster processor, preferably an Intel i5 or better.
At least 4 gigabytes (GB) of memory (RAM), but preferably 8 GB or more.
256 GB hard drive space. (The JavaScript frameworks and Visual Studio Code installations take about 1 GB of hard drive space.)
There are no specific requirements for the graphics display on your machine, although a higher-resolution screen will enable you to see more when writing your programs.
Programming experience
This book will not tell you what programs do or the fundamentals of program creation. You need to know a bit about programming, ideally with JavaScript. The book will put lots of programming techniques into a cloud context. There are many examples you can use as jumping-off points for your own ideas, and we will use the
cloud in many different scenarios, from useful applications to turning lights on and off in your house with the Internet of Things devices to creating compelling shared experiences.
You can write cloud applications in any programming language. But the JavaScript language has been associated with the cloud ever since the language was first built into early web browsers. JavaScript lends itself very well to cloud development, not least because of the huge number of libraries built around it and the ease with which these can be used to develop solutions.
If you have a lot of wonderful JavaScript experience, you’ll be able to get the most from the content immediately. However, if you’ve programmed in any language, you should be able to get the hang of what the sample code is doing. Programming is a universal skill; the programming language is just how you present your program instructions to the computer. So don’t be afraid to have a go just because your background is in C, C++, Java, or Python (to name a few). To make this easier for you, I’ve added an expansive glossary. It contains definitions of terms you might not have seen before, or have seen in a different context. You can find the glossary at https://begintocodecloud.com/glossary.html.
Book Resources
The book content includes 52 code examples, 25 sample applications, and 67 Make Something Happen screencast videos. In the first chapters of the book, you will work with code hosted at the book website at https://begintocodecloud.com/. Later, you will make your own copies of the book resources, which are held on GitHub at https://github.com/Building-Apps-and-Games-in-the-Cloud. Full instructions are in the text.
Errata, updates, and book support
We’ve made every effort to ensure the accuracy of this book and its companion content. You can access updates to this book—in the form of a list of submitted errata and their related corrections—at
MicrosoftPressStore.com/CodeAppsGames/errata
If you discover an error not already listed, please submit it to us at the same page.
If you need additional support, please visit MicrosoftPressStore.com/Support
Please note that product support for Microsoft software and hardware is not offered through the previous addresses. For help with Microsoft software or hardware, go to
http://support.microsoft.com
Stay in touch
Let’s keep the conversation going! We’re on Twitter: http://twitter.com/MicrosoftPress.
Pearson’s Commitment to Diversity, Equity, and Inclusion
Pearson is dedicated to creating bias-free content that reflects the diversity of all learners. We embrace the many dimensions of diversity, including but not limited to race, ethnicity, gender, socioeconomic status, ability, age, sexual orientation, and religious or political beliefs.
Education is a powerful force for equity and change in our world. It has the potential to deliver opportunities that improve lives and enable economic mobility. As we work with authors to create content for every product and service, we acknowledge our responsibility to demonstrate inclusivity and incorporate diverse scholarship so that everyone can achieve their potential through learning. As the world’s leading learning company, we have a duty to help drive change and live up to our purpose to help more people create a better life for themselves and to create a better world.
Our ambition is to purposefully contribute to a world where Everyone has an equitable and lifelong opportunity to succeed through learning.
Our educational products and services are inclusive and represent the rich diversity of learners.
Our educational content accurately reflects the histories and experiences of the learners we serve.
Our educational content prompts deeper discussions with learners and motivates them to expand their own learning (and
While we work hard to present unbiased content, we want to hear from you about any concerns or needs with this Pearson product so that we can investigate and address them.
Please contact us with concerns about any potential bias at https://www.pearson.com/report-bias.html.
Part 1 The cloud
We start by considering where the cloud came from and the drivers behind its development. Then we begin making applications using JavaScript, learning language features and application libraries as we go. By the end of this part, we’ll have built applications running in the browser and also created server code that can run in the cloud.
1 Code and the cloud
What you will learn
In this chapter, we will investigate the fundamentals of cloud computing and discover what makes an application “cloudbased.” We will also start our journey with the JavaScript language by exploring how JavaScript functions allow code running in the browser to interact with the JavaScript environment. We’ll see how programs run inside a web
browser and how we can interact directly with code running in the browser via the Developer Tools, allowing us to view inside our programs as they run.
I’m assuming you are familiar with programming, but just in case there are things that you don’t know (or I have a different understanding), I’ve added a glossary at the end of this book. Whenever you see a word formatted in italic, it means that the word is defined in the glossary. If something doesn’t make sense to you, go to the online glossary at https://begintocodecloud.com/glossary.htmlto see the definition I’m using.
What is the cloud?
JavaScript
JavaScript heroes: functions
Make a console clock
Arrow functions
What you have learned
What is the cloud?
The Internet now underpins many of our daily activities. Things like booking a table at a restaurant, buying a book, or keeping in touch with our friends are now performed using networked services. Nowadays, we refer to these services as “in the cloud.” But what is the cloud? What does it do? And how can we use it? Let’s start with a look at how things were done before we had the cloud.