Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Modern JavaScript Applications
Modern JavaScript Applications
Modern JavaScript Applications
Ebook652 pages4 hours

Modern JavaScript Applications

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • Explore the new features of ECMAScript 6 and how they can be incorporated to build cutting edge web applications
  • Learn about modern web architectures and build real-world apps on top of them
  • Make use of modern JavaScript tools, techniques and frameworks to enhance your web development skills
Who This Book Is For

This book is for existing JavaScript developers who want to explore some of the modern JavaScript features, techniques, and architectures in order to develop cutting-edge web applications.

LanguageEnglish
Release dateJul 25, 2016
ISBN9781785880278
Modern JavaScript Applications
Author

Narayan Prusty

Narayan Prusty is a web and mobile app developer. He specializes in WordPress, HTML5, JavaScript, PHP, Solr, and Cordova. He has been learning and building applications using these technologies for many years. He is the founder of QScutter.com, which provides courses on various application development topics and has more than 10,000 subscribers worldwide. His personal blog, http://www.QNimate.com, is among the top Intel XDK and WordPress blogs. He also works as a consultant and freelance developer for many companies worldwide. Visit him online at http://www.twitter.com/narayanprusty.

Read more from Narayan Prusty

Related to Modern JavaScript Applications

Related ebooks

Programming For You

View More

Related articles

Reviews for Modern JavaScript Applications

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Modern JavaScript Applications - Narayan Prusty

    Table of Contents

    Modern JavaScript Applications

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    eBooks, discount offers, and more

    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. Breaking into Microservices Architecture

    What is monolithic architecture?

    Demerits of monolithic architecture

    Scaling monolithic architecture

    Writing monolithic server-side applications

    Other issues of monolithic architecture

    Microservices architecture to the rescue

    Merits of microservices architecture

    Scaling services

    Demerits of microservices architecture

    When to use microservices architecture

    Data management

    Implementing microservices using Seneca

    Creating your first Seneca application

    Creating actions

    Creating plugins

    Creating services

    Storing data

    Integrating Express and Seneca

    Summary

    2. Building a Coupon Site

    Getting started

    Architecture of our site

    Creating the services

    Database service

    URL config service

    Upload service

    Creating the image upload server

    Creating the monolithic core

    Website walkthrough

    Further improvements to the site

    Summary

    3. Communication between Browsers in Real Time

    Terminologies

    Stream

    Peer-to-peer network model

    Real-time data

    Introduction to WebRTC

    MediaStream API

    navigator.getUserMedia

    RTCPeerConnection API

    Establishing peer-to-peer connection

    Transferring MediaStream

    RTCDataChannel API

    WebRTC applications using PeerJS

    PeerServer

    PeerJS API

    Miscellaneous

    Summary

    4. Building a Chatroulette

    Creating your own PeerServer

    Run PeerServer from shell

    Using PeerServer library

    Creating custom PeerServer

    Integrating PeerServer with the Express server

    Creating a chatroulette

    Building the backend

    Building the frontend

    Testing the website

    Summary

    5. Bidirectional Communication in Real Time

    Introducing WebSocket

    The relationship between WebSocket and HTTP

    Sending and receiving data on a WebSocket connection

    WebSocket schemes

    The interaction of WebSocket with proxy servers, load balancers, and firewalls

    The same-origin policy for WebSocket

    Introduction to Socket.IO

    Setting up your project

    Diving into the Socket.IO API

    Restricting connections based on origin

    Namespaces in Socket.IO

    Referring to all connected Socket.IO clients

    Rooms in Socket.IO

    Joining and leaving a room

    Referring to all connected Socket.IO clients in a room

    Broadcasting messages and custom events to namespaces and rooms

    Broadcasting to a namespace

    Broadcasting to a room

    Middleware in Socket.IO

    Disconnecting manually

    Summary

    6. Building a Live Score Site

    Building the backend

    Integrating socket.io server with the Express server

    Serving static files and HTML to the users

    Serving HTML to the administrator and protecting the admin panel

    Socket.IO cookie authentication and broadcasting messages to a namespace

    Building the frontend

    Testing the website

    Summary

    7. Functional Reactive Programming

    Introduction to reactive programming

    Problems with writing reactive code

    Functional programming in a nutshell

    The advantages of immutable data

    Functional data structures

    The advantages of pure functions

    Functional programming with JavaScript

    Functional programming helper functions

    Getting started with FRP

    EventStreams

    Properties

    FRP using Bacon.js

    Setting up the project

    Bacon.js APIs

    Creating EventStreams

    Creating properties

    Merging, filtering, and transforming EventStreams and properties

    Merging

    Filtering

    Transforming

    Summary

    8. Building an Advanced Profile Search Widget

    Errors in Bacon.js

    Subscribing to errors

    Mapping errors

    Retrying a function call

    Ending an EventStream or property on error

    Handling exceptions

    Constant properties

    An overview of buses

    Subscribing to the end of EventStreams and properties

    Unplugging subscribers

    Combining and zipping

    Lazy evaluation

    Type 1

    Type 2

    Building the profile search widget

    Understanding project directories and files

    Converting Express.js routes to a functional reactive pattern

    Making the user experience better

    The company suggestions route

    The search result route

    Building the frontend

    Testing the widget

    Summary

    9. New Features of Bootstrap 4

    Downloading Bootstrap 4

    Browser and device support

    Understanding the rem and em CSS units

    The grid system

    Global margin reset

    Spacing utility classes

    Display headings

    Inverse tables

    The card component

    Card groups, decks, and columns

    Outline buttons

    Moving from Less to Sass

    Text alignment and float utility classes

    Reboot

    Flexbox support

    JavaScript improvements

    Adding Tether

    The 21:9 aspect ratio class

    Customizing Bootstrap 4

    Glyphicons dropped

    Summary

    10. Building User Interfaces Using React

    Introducing React

    Setting up a basic React project

    Virtual DOM

    Components

    One-way data binding

    Isomorphic UI development

    Getting started with JSX

    Compiling JSX

    JSX syntax

    Digging into components

    Component composition

    Component ownership

    Reconciliation

    Default component property values

    Component life cycle methods

    componentWillMount()

    componentDidMount()

    componentWillReceiveProps(nextProps)

    shouldComponentUpdate(nextProps, nextState)

    componentWillUpdate(nextProps, nextState)

    componentDidUpdate(prevProps, prevState)

    componentWillUnmount()

    Mixins

    Using Refs

    ReactDOMServer.renderToStaticMarkup

    Summary

    11. Building an RSS Reader Using React and Flux

    Understanding Flux

    Using Flux.js

    Using MicroEvent.js

    Introduction to React Router

    Creating the RSS feed reader

    Setting up the project directories and files

    Building the backend

    Building the frontend

    Defining routes

    Creating dispatcher, actions, and stores

    Testing the application

    Summary

    12. New Features of Angular 2

    The Angular 2 architecture

    Introducing web components

    Templates

    Custom elements

    Shadow DOM

    Setting up an Angular 2 project

    Angular 2 fundamentals

    Styling components and shadow DOM

    Angular 2 change detection

    Understanding view children and content children

    Getting the reference of components of content children and view children

    Local template variables

    Component lifecycle methods

    Writing templates

    Rendering a value

    Pipes

    Handling events

    Binding state to element attributes

    Two-way data binding

    Directives

    Attribute directives

    Structural directives

    Outputs

    Two-way data binding with inputs and outputs

    Understanding providers

    The difference between providers and the viewProviders property

    Summary

    13. Building a Search Engine Template Using AngularJS 2

    Setting up the project

    Configuring routes and bootstrapping the app

    Generating random search results

    Creating route components

    Testing the template

    Routing life cycle methods

    Production mode versus development mode

    Summary

    14. Securing and Scaling Node.js Applications

    Common vulnerabilities in applications

    Helmet

    Cross-site request forgery

    Cross-site scripting

    Session fixation

    Non-vulnerability based attacks

    Denial-of-service attacks

    Brute force attacks

    Using secure packages

    Scaling Node.js servers

    Summary

    Index

    Modern JavaScript Applications


    Modern JavaScript Applications

    Copyright © 2016 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 author, 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: July 2016

    Production reference: 1140716

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78588-144-2

    www.packtpub.com

    Credits

    Author

    Narayan Prusty

    Reviewer

    Olivier Pons

    Commissioning Editor

    Wilson D'souza

    Acquisition Editor

    Dharmesh Parmar

    Content Development Editor

    Arshiya Ayaz Umer

    Technical Editor

    Mohit Hassija

    Copy Editor

    Madhusudan Uchil

    Project Coordinator

    Kinjal Bari

    Proofreader

    Safis Editing

    Indexer

    Pratik Shirodkar

    Graphics

    Kirk D'Penha

    Production Coordinator

    Shantanu N. Zagade

    Cover Work

    Shantanu N. Zagade

    About the Author

    Narayan Prusty is a full-stack developer. He works as a consultant for various startups around the world. He has worked on various technologies and programming languages but is very passionate about JavaScript, WordPress, Ethereum, Solr, React, Cordova, MongoDB, and AWS.

    Apart from consulting for various startups, he also runs a blog titled QNimate (http://qnimate.com) and a video-tutorial site titled QScutter (http://qscutter.com), where he shares information about a lot of the technologies he works on. Previously, he wrote a book titled Learning ECMAScript 6, which was published by Packt Publishing.

    You can reach Narayan on LinkedIn (https://in.linkedin.com/in/narayanprusty).

    About the Reviewer

    Olivier Pons is a senior developer who's been building websites for many years. He's a teacher at the University of Sciences (IUT) of Aix-en-Provence, France, ISEN (Institut Supérieur de l'Électronique et du Numérique), G4 Marseille, and École d'Ingénieurs des Mines de Gardanne, where he teaches state-of-the-art web techniques: Node.js, big data/NoSQL, MVC fundamentals, Django/Python, Symfony basics, Wordpress, PHP, HTML, CSS, jQuery/jQuery mobile, AngularJS, Apache, Linux basics, and advanced VIM techniques. He has already done some technical reviews, including the Packt books Learning ExtJS, ExtJS 4 First Look, jQuery hotshots, jQuery Mobile Web Development Essentials, Wordpress 4 Complete, and jQuery 2.0 for Designers Beginner's Guide. In 2011, he left a full-time job as a Delphi developer and PHP expert to concentrate on his own company, HQF Development (http://hqf.fr). He currently runs a number of websites, including http://krystallopolis.fr, http://artsgaleries.com, http://www.battlesoop.fr, http://www.cogofly.com, http://www.papdevis.fr, and http://olivierpons.fr, his own web development blog. He's currently polishing http://cogofly.com and making a keyboard for geek here http://ergofip.com. He works as a consultant, teacher, and project manager and sometimes helps big companies as a senior/highly skilled developer.

    www.PacktPub.com

    eBooks, discount offers, and more

    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 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.

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Preface

    The book begins by covering an enterprise-level application with the microservices architecture, using Node.js to build web services. As we move forward, the book shows you how to build a browser-browser application using WebRTC. We then focus on building a real-time web application with WebSockets.

    When you've gained a solid grip on the different architectures, you'll see how to write better reactive code using functional reactive programming (FRP). Then, we'll move onto what's new in Bootstrap 4 and how it makes it easier then ever to build responsive sites. As we near the end of this book, you'll see how to build a modern single-page application that builds on the innovative component-based architecture using React and Angular 2.

    After reading this book, you will have a solid knowledge of the latest JavaScript techniques, tools, and architecture required to build modern web apps.

    What this book covers

    Chapter 1, Breaking into Microservices Architecture, teaches what the microservices architecture is and why enterprise-level applications are built using it. We will then explore Seneca.js, which is a microservices toolkit for Node.js.

    Chapter 2, Building a Coupon Site, shows you how to build a basic coupon site to demonstrate Seneca.js and the microservices architecture.

    Chapter 3, Communication between Browsers in Real Time, teaches you what WebRTC is and how to use it to implement features such as audio/video chat or some other features in websites that need real-time browser-to-browser data transfer or to retrieve audio/video streams from microphones, webcams, or any other device. We will learn to write WebRTC-based applications using PeerJS, which simplifies WebRTC-based application development.

    Chapter 4, Building a Chatroulette, shows you how to build a chatroulette to demonstrate WebRTC and PeerJS.

    Chapter 5, Bidirectional Communication in Real Time, teaches what WebSockets are and how to achieve bidirectional communication in real-time using WebSockets. We will then explore Socket.IO, which utilizes WebSockets to enable bidirectional communication in real time.

    Chapter 6, Building a Live Score Site, shows you how to build a simple live-score site using Socket.IO.

    Chapter 7, Functional Reactive Programming, teaches you reactive code and how to write better reactive code using functional reactive programming. We will then explore Bacon.js, which is a functional reactive programming library for JavaScript.

    Chapter 8, Building an Advanced Profile Search Widget, helps you build an advanced profile-search widget using Bacon.js.

    Chapter 9, New Features of Bootstrap 4, teaches you what's new in Bootstrap 4 and how it makes it easier then ever to create responsive sites.

    Chapter 10, Building User Interfaces Using React, teaches you what React.js is and how it makes writing of code for reactive UI easier and takes care of rendering performance and reusability.

    Chapter 11, Building an RSS Reader Using React and Flux, shows you how to build a simple RSS reader using React and the Flux architecture.

    Chapter 12, New Features of Angular 2, teaches you how to use Angular 2 to build the client side of websites. We will also learn about web components in this chapter.

    Chapter 13, Building a Search Engine Template Using AngularJS 2, shows you how to build a search engine template using Angular 2. We will also learn how to build an SPA using Angular 2.

    Chapter 14, Securing and Scaling Node.js Applications, teaches you how to make Node.js applications more secure and what the common technologies used for scaling Node.js applications are.

    What you need for this book

    You can use any operating system that supports Node.js and MongoDB. You will need a browser, but I would recommended you to use the latest version of Chrome as it's way ahead with supporting the new technologies that are covered in this book. You will also need a webcam and microphone. And finally, you will need a working Internet connection.

    Who this book is for

    This book is for existing JavaScript developers who want to explore some modern JavaScript features, techniques, and architectures in order to develop cutting-edge web applications.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Here we are first calling the make method of the senena object. It's used to get reference of an entity's store. For example, in case of MySQL, the make method gets reference to a table.

    A block of code is set as follows:

    var script_start_time = Bacon.constant(Date.now()).map(function(value){

      var date = new Date(value);

      return (date).getHours() + : + (date).getMinutes() + : + (date).getSeconds();

    });

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Now click on the Admin button to visit the admin panel and accept the coupon. Here is how the admin panel will look.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

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

    To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in 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 at 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 this book 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.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Modern-JavaScript-Applications. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Downloading the color images of this book

    We also provide you with 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 https://www.packtpub.com/sites/default/files/downloads/ModernJavaScriptApplications_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 could 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 Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted 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 <copyright@packtpub.com> 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

    If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.

    Chapter 1. Breaking into Microservices Architecture

    The architecture of server-side application development for complex and large applications (applications with huge number of users and large volume of data) shouldn't just involve faster response and providing web services for wide variety of platforms. It should be easy to scale, upgrade, update, test, and deploy. It should also be highly available, allowing the developers write components of the server-side application in different programming languages and use different databases. Therefore, this leads the developers who build large and complex applications to switch from the common monolithic architecture to microservices architecture that allows us to do all this easily. As microservices architecture is being widely used in enterprises that build large and complex applications, it's really important to learn how to design and create server-side applications using this architecture. In this chapter, we will discuss how to create applications based on microservices architecture with Node.js using the Seneca toolkit.

    In this chapter, we'll cover the following topics:

    Understanding monolithic architecture

    Scaling, upgrading, deploying, and writing applications based on monolithic architecture

    Discussing microservices architecture in depth

    Scaling, upgrading, deploying, and writing applications based on microservices architecture

    Getting started with Seneca

    Creating and calling services using Seneca

    What is monolithic architecture?

    To understand microservices architecture, it's important to first understand monolithic architecture, which is its opposite.

    In monolithic architecture, different functional components of the server-side application, such as payment processing, account management, push notifications, and other components, all blend together in a single unit.

    For example, applications are usually divided into three parts. The parts are HTML pages or native UI that run on the user's machine, server-side application that runs on the server, and database that also runs on the server. The server-side application is responsible for handling HTTP requests, retrieving and storing data in a database, executing algorithms, and so on. If the server-side application is a single executable (that is, running is a single process) that does all these tasks, then we say that the server-side application is monolithic.

    This is a common way of building server-side applications. Almost every major CMS, web servers, server-side frameworks, and so on are built using monolithic architecture.

    This architecture may seem successful, but problems are likely to arise when your application is large and complex.

    Demerits of monolithic architecture

    The following are some of the issues caused by server-side applications built using the monolithic architecture.

    Scaling monolithic architecture

    As traffic to your server-side application increases, you will need to scale your server-side application to handle the traffic.

    In case of monolithic architecture, you can scale the server-side application by running the same executable on multiple servers and place the servers behind a load balancer or you can use round robin DNS to distribute the traffic among the servers:

    In the preceding diagram, all the servers will be running the same server-side application.

    Although scaling is easy, scaling monolithic server-side application ends up with scaling all the components rather than the components that require greater resource. Thus, causing unbalanced utilization of resources sometimes, depending on the quantity and types of resources the components need.

    Let's consider some examples to understand the issues caused while scaling monolithic server-side applications:

    Suppose there is a component of server-side application that requires a more

    Enjoying the preview?
    Page 1 of 1