JavaScript Frameworks for Modern Web Dev 1st Edition Ambler Tim - Download the ebook now to never miss important content
JavaScript Frameworks for Modern Web Dev 1st Edition Ambler Tim - Download the ebook now to never miss important content
com
https://textbookfull.com/product/javascript-frameworks-for-
modern-web-dev-1st-edition-ambler-tim/
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/web-application-security-
exploitation-and-countermeasures-for-modern-web-applications-1st-
edition-andrew-hoffman/
textbookfull.com
https://textbookfull.com/product/web-application-security-
exploitation-and-countermeasures-for-modern-web-applications-1st-
edition-andrew-hoffman-2/
textbookfull.com
https://textbookfull.com/product/javascript-on-things-hacking-
hardware-for-web-developers-lyza-danger-gardner/
textbookfull.com
https://textbookfull.com/product/learn-java-for-web-development-
modern-java-web-development-layka-vishal/
textbookfull.com
https://textbookfull.com/product/javascript-cookbook-programming-the-
web-3rd-edition-scott/
textbookfull.com
PHP Web Services APIs for the Modern Web 2nd Edition Lorna
Jane Mitchell
https://textbookfull.com/product/php-web-services-apis-for-the-modern-
web-2nd-edition-lorna-jane-mitchell/
textbookfull.com
https://textbookfull.com/product/ultimate-modern-jquery-for-web-app-
development-1st-edition-laurence-svekis/
textbookfull.com
I
Fa Ma Kn Re Grun nclu
ye ch oc q t, de
, Q , ko uir Ye s B
, A Mo ut eJ om o
sy ng , A S,B a we
nc o ng ro n, r,
.js ose ul w PM
, U , ar se 2
nd K n JS, rif ,
er ex, Kr y,
sco B ak
re, ook en
an she ,
d L lf,
od
as
h
www.it-ebooks.info
JavaScript Frameworks
for Modern Web Dev
Tim Ambler
Nicholas Cloud
www.it-ebooks.info
JavaScript Frameworks for Modern Web Dev
Copyright © 2015 by Tim Ambler and Nicholas Cloud
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with
reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed
on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or
parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its
current version, and permission for use must always be obtained from Springer. Permissions for use may be
obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under
the respective Copyright Law.
ISBN-13 (pbk): 978-1-4842-0663-8
ISBN-13 (electronic): 978-1-4842-0662-1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director: Welmoed Spahr
Lead Editor: Louise Corrigan
Technical Reviewer: Robin Hawkes
Editorial Board: Steve Anglin, Mark Beckner, Gary Cornell, Louise Corrigan, James DeWolf,
Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie,
Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing, Matt Wade, Steve Weiss
Coordinating Editor: Kevin Walter
Copy Editor: Bill McManus
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Cover Designer: Crest
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special
Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this text is available to
readers at www.apress.com/. For detailed information about how to locate your book’s source code, go to
www.apress.com/source-code/.
www.it-ebooks.info
There was a young lady named Laura,
Who was a beautiful señora.
Her love and assurance
Was a frequent occurrence
Which allowed me to write this book for yah.
—Tim
www.it-ebooks.info
Contents at a Glance
■
■Chapter 1: Bower��������������������������������������������������������������������������������������������������� 1
■
■Chapter 2: Grunt�������������������������������������������������������������������������������������������������� 11
■
■Chapter 3: Yeoman���������������������������������������������������������������������������������������������� 37
■
■Chapter 4: PM2���������������������������������������������������������������������������������������������������� 53
■
■Chapter 5: RequireJS������������������������������������������������������������������������������������������� 73
■
■Chapter 6: Browserify���������������������������������������������������������������������������������������� 101
■
■Chapter 7: Knockout������������������������������������������������������������������������������������������ 121
■
■Chapter 8: AngularJS���������������������������������������������������������������������������������������� 155
■
■Chapter 9: Kraken���������������������������������������������������������������������������������������������� 191
■
■Chapter 10: Mach���������������������������������������������������������������������������������������������� 251
■
■Chapter 11: Mongoose��������������������������������������������������������������������������������������� 297
■
■Chapter 12: Knex and Bookshelf����������������������������������������������������������������������� 345
■
■Chapter 13: Faye������������������������������������������������������������������������������������������������ 381
www.it-ebooks.info
■ Contents at a Glance
■
■Chapter 14: Q����������������������������������������������������������������������������������������������������� 395
■
■Chapter 15: Async.js����������������������������������������������������������������������������������������� 425
■
■Chapter 16: Underscore and Lodash����������������������������������������������������������������� 447
Index��������������������������������������������������������������������������������������������������������������������� 477
vi
www.it-ebooks.info
Contents
■
■Chapter 1: Bower��������������������������������������������������������������������������������������������������� 1
Getting Started����������������������������������������������������������������������������������������������������������������� 2
Configuring Bower������������������������������������������������������������������������������������������������������������ 2
The Manifest�������������������������������������������������������������������������������������������������������������������� 2
Creating a New Manifest������������������������������������������������������������������������������������������������������������������������ 3
Semantic Versioning��������������������������������������������������������������������������������������������������������� 6
Managing the Dependency Chain������������������������������������������������������������������������������������� 7
Creating Bower Packages������������������������������������������������������������������������������������������������ 8
Choose a Valid Name������������������������������������������������������������������������������������������������������������������������������ 8
Use Semver Git Tags������������������������������������������������������������������������������������������������������������������������������� 8
Publish Your Package to the Registry����������������������������������������������������������������������������������������������������� 9
Summary�������������������������������������������������������������������������������������������������������������������������� 9
vii
www.it-ebooks.info
■ Contents
■
■Chapter 2: Grunt�������������������������������������������������������������������������������������������������� 11
Installing Grunt��������������������������������������������������������������������������������������������������������������� 12
How Grunt Works������������������������������������������������������������������������������������������������������������ 12
Gruntfile.js�������������������������������������������������������������������������������������������������������������������������������������������� 12
Tasks���������������������������������������������������������������������������������������������������������������������������������������������������� 14
Plugins�������������������������������������������������������������������������������������������������������������������������������������������������� 14
Configuration���������������������������������������������������������������������������������������������������������������������������������������� 15
Creating Plugins������������������������������������������������������������������������������������������������������������� 32
Getting Started������������������������������������������������������������������������������������������������������������������������������������� 32
Creating the Task���������������������������������������������������������������������������������������������������������������������������������� 32
Publishing to npm��������������������������������������������������������������������������������������������������������������������������������� 35
Summary������������������������������������������������������������������������������������������������������������������������ 36
Related Resources��������������������������������������������������������������������������������������������������������� 36
viii
www.it-ebooks.info
■ Contents
■
■Chapter 3: Yeoman���������������������������������������������������������������������������������������������� 37
Installing Yeoman����������������������������������������������������������������������������������������������������������� 38
Creating Your First Project���������������������������������������������������������������������������������������������� 38
Subcommands�������������������������������������������������������������������������������������������������������������������������������������� 41
Summary������������������������������������������������������������������������������������������������������������������������ 52
Related Resources��������������������������������������������������������������������������������������������������������� 52
■
■Chapter 4: PM2���������������������������������������������������������������������������������������������������� 53
Installation���������������������������������������������������������������������������������������������������������������������� 53
Working with Processes������������������������������������������������������������������������������������������������� 54
Recovering from Errors������������������������������������������������������������������������������������������������������������������������ 56
Responding to File Changes����������������������������������������������������������������������������������������������������������������� 58
Monitoring Logs������������������������������������������������������������������������������������������������������������� 58
Monitoring Resource Usage������������������������������������������������������������������������������������������� 60
Monitoring Local Resources����������������������������������������������������������������������������������������������������������������� 60
Monitoring Remote Resources������������������������������������������������������������������������������������������������������������� 61
Advanced Process Management������������������������������������������������������������������������������������ 63
JSON Application Declarations������������������������������������������������������������������������������������������������������������� 63
Summary������������������������������������������������������������������������������������������������������������������������ 72
Related Resources��������������������������������������������������������������������������������������������������������� 72
ix
www.it-ebooks.info
■ Contents
■
■Chapter 5: RequireJS������������������������������������������������������������������������������������������� 73
Running the Examples���������������������������������������������������������������������������������������������������� 74
Working with RequireJS������������������������������������������������������������������������������������������������� 74
Installation�������������������������������������������������������������������������������������������������������������������������������������������� 75
Configuration���������������������������������������������������������������������������������������������������������������������������������������� 75
Application Modules and Dependencies����������������������������������������������������������������������������������������������� 78
Paths and Aliases��������������������������������������������������������������������������������������������������������������������������������� 81
Shims���������������������������������������������������������������������������������������������������������������������������������������������������� 84
Loader Plugins�������������������������������������������������������������������������������������������������������������������������������������� 88
Cache Busting��������������������������������������������������������������������������������������������������������������������������������������� 94
RequireJS Optimizer������������������������������������������������������������������������������������������������������� 96
Configuring r.js������������������������������������������������������������������������������������������������������������������������������������� 96
Running the r.js Command������������������������������������������������������������������������������������������������������������������� 97
Summary������������������������������������������������������������������������������������������������������������������������ 99
■
■Chapter 6: Browserify���������������������������������������������������������������������������������������� 101
The AMD API vs. CommonJS���������������������������������������������������������������������������������������� 102
Installing Browserify���������������������������������������������������������������������������������������������������� 102
Creating Your First Bundle�������������������������������������������������������������������������������������������� 103
Visualizing the Dependency Tree���������������������������������������������������������������������������������� 104
Creating New Bundles As Changes Occur�������������������������������������������������������������������� 105
Watching for File Changes with Grunt������������������������������������������������������������������������������������������������ 106
Watching for File Changes with Watchify������������������������������������������������������������������������������������������� 106
www.it-ebooks.info
■ Contents
Summary���������������������������������������������������������������������������������������������������������������������� 120
Related Resources������������������������������������������������������������������������������������������������������� 120
■
■Chapter 7: Knockout������������������������������������������������������������������������������������������ 121
Views, Models, and View Models��������������������������������������������������������������������������������� 122
The Recipe List����������������������������������������������������������������������������������������������������������������������������������� 124
Recipe Details������������������������������������������������������������������������������������������������������������������������������������� 127
xi
www.it-ebooks.info
■ Contents
■
■Chapter 8: AngularJS���������������������������������������������������������������������������������������� 155
A Declarative Approach to Building Web Applications�������������������������������������������������� 155
The Imperative Approach�������������������������������������������������������������������������������������������������������������������� 155
The Declarative Approach������������������������������������������������������������������������������������������������������������������� 157
xii
www.it-ebooks.info
■ Contents
Summary���������������������������������������������������������������������������������������������������������������������� 250
Related Resources������������������������������������������������������������������������������������������������������� 250
■
■Chapter 10: Mach���������������������������������������������������������������������������������������������� 251
Chapter Examples�������������������������������������������������������������������������������������������������������� 251
Installation�������������������������������������������������������������������������������������������������������������������� 252
Mach, the Web Server�������������������������������������������������������������������������������������������������� 252
HTTP Routes��������������������������������������������������������������������������������������������������������������������������������������� 254
Making Connections��������������������������������������������������������������������������������������������������������������������������� 260
Common Middleware�������������������������������������������������������������������������������������������������������������������������� 262
These Are Not the Routes You’re Looking for������������������������������������������������������������������������������������� 280
The Hosts with the Most��������������������������������������������������������������������������������������������������������������������� 282
Custom Middleware���������������������������������������������������������������������������������������������������������������������������� 287
xiii
www.it-ebooks.info
■ Contents
■
■Chapter 11: Mongoose��������������������������������������������������������������������������������������� 297
Basic MongoDB Concepts�������������������������������������������������������������������������������������������� 297
A Simple Mongoose Example��������������������������������������������������������������������������������������� 300
Creating a Mongoose Schema for JSON Data������������������������������������������������������������������������������������ 301
Importing Data with Mongoose���������������������������������������������������������������������������������������������������������� 302
Querying Data with Mongoose����������������������������������������������������������������������������������������������������������� 305
www.it-ebooks.info
■ Contents
Bookshelf��������������������������������������������������������������������������������������������������������������������� 361
What Is an Object-Relational Mapper?����������������������������������������������������������������������������������������������� 361
Creating Your First Bookshelf Model��������������������������������������������������������������������������������������������������� 362
Relationships�������������������������������������������������������������������������������������������������������������������������������������� 370
Summary���������������������������������������������������������������������������������������������������������������������� 379
Related Resources������������������������������������������������������������������������������������������������������� 379
■
■Chapter 13: Faye������������������������������������������������������������������������������������������������ 381
HTTP, Bayeux, and WebSockets������������������������������������������������������������������������������������ 381
WebSockets���������������������������������������������������������������������������������������������������������������������������������������� 383
The Bayeux Protocol��������������������������������������������������������������������������������������������������������������������������� 384
Summary���������������������������������������������������������������������������������������������������������������������� 393
Related Resources������������������������������������������������������������������������������������������������������� 394
■
■Chapter 14: Q����������������������������������������������������������������������������������������������������� 395
Timing Is Everything����������������������������������������������������������������������������������������������������� 395
Promises vs. Callbacks������������������������������������������������������������������������������������������������ 399
The Promise of Q���������������������������������������������������������������������������������������������������������� 401
Deferreds and Promises��������������������������������������������������������������������������������������������������������������������� 401
Values and Errors������������������������������������������������������������������������������������������������������������������������������� 406
Reporting Progress����������������������������������������������������������������������������������������������������������������������������� 412
Everything Ends���������������������������������������������������������������������������������������������������������������������������������� 415
Summary���������������������������������������������������������������������������������������������������������������������� 423
Related Resources������������������������������������������������������������������������������������������������������� 423
xv
www.it-ebooks.info
■ Contents
■
■Chapter 15: Async.js����������������������������������������������������������������������������������������� 425
Sequential Flow������������������������������������������������������������������������������������������������������������ 426
Parallel Flow����������������������������������������������������������������������������������������������������������������� 428
Pipeline Flow���������������������������������������������������������������������������������������������������������������� 430
Reusing a Pipeline������������������������������������������������������������������������������������������������������������������������������ 433
Summary���������������������������������������������������������������������������������������������������������������������� 446
■
■Chapter 16: Underscore and Lodash����������������������������������������������������������������� 447
Installation and Usage�������������������������������������������������������������������������������������������������� 449
Aggregation and Indexing�������������������������������������������������������������������������������������������� 449
countBy( )�������������������������������������������������������������������������������������������������������������������������������������������� 449
groupBy( )�������������������������������������������������������������������������������������������������������������������������������������������� 451
indexBy( )�������������������������������������������������������������������������������������������������������������������������������������������� 452
Chaining����������������������������������������������������������������������������������������������������������������������� 460
Function Timing������������������������������������������������������������������������������������������������������������ 463
defer( )������������������������������������������������������������������������������������������������������������������������������������������������ 463
debounce( )����������������������������������������������������������������������������������������������������������������������������������������� 465
throttle( )��������������������������������������������������������������������������������������������������������������������������������������������� 466
xvi
www.it-ebooks.info
■ Contents
Templates��������������������������������������������������������������������������������������������������������������������� 468
Loops and Other Arbitrary JavaScript in Templates���������������������������������������������������������������������������� 470
Living Without Gator Tags������������������������������������������������������������������������������������������������������������������� 472
Accessing the Data Object Within a Template������������������������������������������������������������������������������������ 473
Default Template Data������������������������������������������������������������������������������������������������������������������������ 474
Summary���������������������������������������������������������������������������������������������������������������������� 475
Related Resources������������������������������������������������������������������������������������������������������� 476
Index��������������������������������������������������������������������������������������������������������������������� 477
xvii
www.it-ebooks.info
About the Authors
Nicholas Cloud is a software developer who lives in the very humid city of
St. Louis. For over a decade he has forged his skills into a successful career.
He has developed web applications, web services, and desktop software on
diverse platforms with JavaScript, C#, and PHP. A strong proponent of open
source software, Nicholas contributes to userland projects and has written
several of his own open source libraries libraries. He speaks at a variety of
user groups and conferences and writes books, technical articles, and blog
posts in his spare time. He opines on Twitter at @nicholascloud.
xix
www.it-ebooks.info
About the Technical Reviewer
xxi
www.it-ebooks.info
Acknowledgments
This book would not have been possible without the encouragement and support of a number of people:
Nicholas Cloud, my friend and co-author, without whom this book would be much more limited
in scope and depth. His knowledge, experience, and steadfast dedication to this project have been
immeasurably helpful. Thank you.
Louise Corrigan, Kevin Walter, Christine Ricketts, Melissa Maldonado, and the rest of the staff at Apress
who supported us throughout the course of this project. I am grateful for the invitation that was extended to
embark upon this journey and for the ongoing support that you have provided.
Robin Hawkes, our technical reviewer. The examples and source code included with this book have
greatly benefited from his keen insight and sharp eye.
James Coglan, the creator of Faye. Thank you for taking the time to share your technical expertise
and feedback.
My friends and colleagues Greg Jones, Jeff Crump, Seth Steele, Jon Zumbrun, and Brian Hiatt. I am
grateful for your feedback and encouragement.
—Tim
Acknowledgements are slippery things. I have so many debts, and so little space to repay.
First, the debt to my co-author Tim who reached out and invited me on this journey. We’ve never met
in person but worked remotely as co-workers for about half a year—enough time for each of us to leave an
impression on each other across the miles. For his trust, encouragement, and constant effort I am grateful.
Second, my debt to the staff at Apress who guided us through the publishing process: Kevin, Louise,
Christine, and Melissa. Their patience and careful guidance spared you, the reader, from no small amount of
cringes, and kept me on my toes during the entire writing process. They are all sharp professionals with whom
I hope to work again some day.
Third, I am indebted to Robin for his excellent technical reviews; for reading and executing more code
samples than a developer should ever be tasked with groking.
Finally, I cannot repay the subject-matter expertise I gleaned from Michael Jackson (@mjackson) while
researching Mach, and Ryan Niemeyer (@RPNiemeyer) while researching Knockout—I can only pay it forward
to you, the reader.
—Nicholas
xxiii
www.it-ebooks.info
Introduction
They tell me we’re living in an information age, but none of it seems to be the information
I need or brings me closer to what I want to know. In fact (I’m becoming more and more
convinced) all this electronic wizardry only adds to our confusion, delivering inside scoops
and verdicts about events that have hardly begun: a torrent of chatter moving at the speed
of light, making it nearly impossible for any of the important things to be heard.
—Matthew Flaming, The Kingdom of Ohio
The notion that “technology moves quickly” is a well-worn aphorism, and with good reason: technology
does move quickly. But at this moment, JavaScript in particular is moving very quickly indeed—much like
that “torrent of chatter moving at the speed of light” that Matthew Flaming refers to in The Kingdom of Ohio.
The language is in the midst of what many have called a renaissance, brought about by the rapidly increasing
sophistication of browser-based applications and the rising popularity of JavaScript on the server, thanks to
Node.js.
An almost feverish pace of innovation is occurring within the JavaScript community that, while
endlessly fascinating to follow, also presents some unique challenges of its own. JavaScript’s ecosystem of
libraries, frameworks, and utilities has grown dramatically. Where once a small number of solutions for any
given problem existed, many can now be found… and the options continue to grow by the day. As a result,
developers find themselves faced with the increasingly difficult task of choosing the appropriate tools from
among many seemingly good options.
If you’ve ever found yourself wondering why JavaScript seems to be attracting so much attention lately,
as we have, it’s worth stopping for a moment to consider the fact that JavaScript, a language that was created
by one person in ten days, now serves as the foundation upon which much of the Web as we know it sits.
A language that was originally created to solve relatively simple problems is now being applied in new
and innovative ways that were not originally foreseen. What’s more, JavaScript is a beautifully expressive
language, but it’s not without its share of rough edges and potential pitfalls. While flexible, efficient, and
ubiquitous, JavaScript concepts such as the event loop and prototypal inheritance can prove particularly
challenging for those coming to the language for the first time.
For these and many other reasons, the development community at large is still coming to terms with
how best to apply the unique features that JavaScript brings to the table. We’ve no doubt only scratched
the surface of what the language and the community behind it are capable of. For those with an insatiable
appetite for knowledge and a desire to create, now is the perfect time to be a JavaScript developer.
We have written Pro JavaScript Frameworks for Modern Web Dev to serve as your guide to a wide
range of popular JavaScript tools that solve difficult problems at both ends of the development stack: in
the browser and on the server. The tutorials and downloadable code examples contained within this book
illustrate the usage of tools that manage dependencies, structure code in a modular fashion, automate
repetitive build tasks, create specialized servers, structure client side applications, facilitate horizontal
scaling, perform event logging, and interacting with disparate data stores.
The libraries and frameworks covered include Bower, Grunt, Yeoman, PM2, RequireJS, Browserify,
Knockout, AngularJS, Kraken, Mach, Mongoose, Knex, Bookshelf, Faye, Q, Async.js, Underscore, and Lodash.
xxv
www.it-ebooks.info
■ Introduction
In writing Pro JavaScript Frameworks for Modern Web Dev, our goal was to create a filter for the
“torrent of chatter” that often seems to surround JavaScript, and in so doing, to allow what we believe are
some important things to be heard. We hope the information contained within these pages proves as useful
to you as it has to us.
Grunt
Larry Wall, the creator of Perl, describes the three virtues of a great programmer as: laziness, impatience,
and hubris. In this chapter, we’ll focus on a tool that will help you strengthen the virtue of laziness - Grunt.
This popular task runner provides developers with a framework for creating command-line utilities
that automative repetitive build tasks such as running tests, concatenating files, compiling SASS / LESS
stylesheets, checking for JavaScript errors, and more. After reading this chapter, you’ll know how to use several
popular Grunt plugins, as well as how to go about creating and sharing your own plugins with the community.
xxvi
www.it-ebooks.info
■ Introduction
Yeoman
Yeoman provides JavaScript developers with a mechanism for creating reusable templates (“generators”)
that describe the overall structure of a project (initially required dependencies, Grunt tasks, etc…) in a way
that can be easily re-used over and over. Broad community support also allows you to take advantage of a
wide variety of pre-existing templates. In this chapter, we’ll walk through the process of installing Yeoman
and using several popular pre-existing generators. Finally, we’ll take a look at how we can create and share
our own templates with the community.
PM2
In this chapter, we will close out our discussion of development tools by taking a look at PM2, a command-line
utility that simplifies many of the tasks associated with running Node applications, monitoring their status,
and efficiently scaling them to meet increasing demand.
xxvii
www.it-ebooks.info
■ Introduction
Part 6: Communication
Faye
In this section, you’ll be introduced to Faye, a Node.js library that provides developers with a robust and
easy-to-use platform for building products that rely on real-time communication between servers and all
major browsers.Much of Faye’s popularity stems from the project’s goal of working everywhere the Web
works. Faye accomplishes this by providing seamless fallback support for a number of communication
protocols.
xxviii
www.it-ebooks.info
■ Introduction
Most examples are run with the Node.js runtime, which may be obtained from https://nodejs.org.
Chapters with additional prerequisites will explain the necessary procedures for downloading and
installing the examples. (For example, MongoDB is necessary to run examples in Chapter 11, which covers
Mongoose.)
Any additional steps necessary for running code examples (e.g., executing curl requests) or interacting
with a running example (e.g., opening a web browser and navigating to a specific URL) are explained
alongside each listing.
xxix
www.it-ebooks.info
Chapter 1
Bower
The concept of package management, also known as dependency management, is not new. Utilities within
this category provide developers with a mechanism for managing the various third-party libraries that a
project relies on. Widely used examples include
• npm: The package manager for Node.js
• Composer: A tool for dependency management in PHP
• pip: The PyPA recommended tool for installing Python packages
• NuGet: The package manager for the Microsoft development platform including .NET
While package management is hardly a new idea, a practice that has only recently begun to see
widespread adoption is the application of this concept to the management of front-end web assets—the
JavaScript libraries, stylesheets, fonts, icons, and images that serve as the building blocks of modern web
applications. The need for such structure has become evident as the foundations on which modern web
applications are built have grown in complexity. Web applications that once relied on a small selection of
broadly defined, “one size fits all” third-party libraries (e.g., jQuery) now find themselves using the work
of many more smaller libraries, each with a tightly defined purpose. Benefits of this approach include
smaller modules that are easier to test, as well as an enhanced degree of flexibility on the part of the
parent application, which can more easily extend third-party libraries or replace them altogether when
necessary.
This chapter is designed to get you up and running quickly with Bower, the front-end package manager
whose roots lie in open source initiatives at Twitter. Topics covered include
• Installing and configuring Bower
• Adding Bower to a project
• Finding, adding, and removing packages
• Semantic Versioning
• Managing the dependency chain
• Creating Bower packages
www.it-ebooks.info
Chapter 1 ■ Bower
Getting Started
All interaction with Bower occurs through a command-line utility that can be installed via npm. If you do not
already have Bower installed, you should install it before you continue, as shown in Listing 1-1.
■■Note Node’s package manager (npm) allows users to install packages in one of two contexts: locally
or globally. In this example, bower is installed within the global context, which is typically reserved for
command-line utilities.
Configuring Bower
Bower is configured on a per-project basis through a single (optional) JSON file that exists in your project’s
root folder, .bowerrc. For the purposes of this introduction, we’ll only look at the most frequently changed
setting within this file (see Listing 1-2).
Listing 1-2. The .bowerrc File from This Chapter’s Sample Project
// example-bootstrap/.bowerrc
{
"directory": "./public/bower_components"
}
By default, Bower will store your project’s dependencies in the bower_components folder. You will likely
want to change this location, and the directory setting allows you to do so.
The Manifest
Bower provides developers with a single point of entry from which third-party libraries can be found, added,
upgraded, and removed. As these actions occur, Bower updates a JSON file referred to as the “manifest”
with an up-to-date list of the project’s dependencies. The Bower manifest for this chapter’s sample project is
shown in Listing 1-3. In this example, Bower is aware of a single dependency, the Bootstrap CSS framework.
{
"name": "example-bootstrap",
"version": "1.0.0",
"homepage": "https://github.com/username/project",
www.it-ebooks.info
Chapter 1 ■ Bower
"authors": [
"John Doe <john.doe@gmail.com>"
],
"dependencies": {
"bootstrap": "3.2.0"
}
}
If we were to accidentally delete all of our project’s dependencies by removing the public/bower_
components folder, we could easily restore our project to its previous state by issuing a single command, as
shown next. Doing so would cause Bower to compare its manifest with our project’s current file structure,
determine what dependencies are missing, and restore them.
$ bower install
As a result of this behavior, we have the option of ignoring our project’s /public/bower_components
folder within version control. By committing only Bower’s manifest, and not the dependencies themselves,
our project’s source code can be kept in a cleaner state, containing only files that pertain directly to our
own work.
■■Note Opinions differ as to whether or not keeping your project’s dependencies out of version control is
a good idea. On the one hand, doing so results in a cleaner repository. On the other hand, this also opens the
door to potential problems should you (or the Bower registry, or GitHub, etc.) encounter connection issues.
The general consensus seems to be that if you are working on a “deployable” project (i.e., an application,
not a module), committing your dependencies is the preferred approach. Otherwise, keeping your project’s
dependencies out of version control is probably a good idea.
$ bower init
Finding Packages
One of the primary ways in which Bower can improve your development workflow is by providing you with a
centralized registry from which third-party libraries can be found. To search the Bower registry, simply pass
the search argument to Bower, followed by a keyword to search for, as shown in Listing 1-4. In this example,
only a short excerpt from the returned list of search results is shown.
www.it-ebooks.info
Chapter 1 ■ Bower
Search results:
jquery git://github.com/jquery/jquery.git
jquery-ui git://github.com/components/jqueryui
jquery.cookie git://github.com/carhartl/jquery-cookie.git
jquery-placeholder git://github.com/mathiasbynens/jquery-placeholder.git
Adding Packages
Each search result includes the name under which the package was registered, along with the URL of the
GitHub repository at which it can be accessed directly. Once we have located the desired package, we can
add it to our project as shown in Listing 1-5.
jquery#2.1.3 public/bower_components/jquery
■■Note Bower does not host any of the files associated with the packages contained within its registry; it
defers to GitHub for that responsibility. While it is possible to host packages at any URL, the majority of public
packages are found on GitHub.
Take note of the fact that in Listing 1-5, we pass the --save option to Bower’s install command. By
default, the install command will add the requested package to a project without updating its manifest.
By passing the --save option, we instruct Bower to permanently store this package within its list of
dependencies.
Listing 1-6 shows the HTML from this chapter’s sample project. After adding jQuery to our project via
Bower, we can load it via a script tag as we would any other library.
www.it-ebooks.info
Random documents with unrelated
content Scribd suggests to you:
Biron’s Plot.
An attempt by the Baron de Biron, one of the King’s most trusted
generals, to unite the Catholic and Huguenot malcontents against Henri IV,
in conjunction with a league of Spain and Savoy against the French king.
The plot was betrayed by a subordinate, named La Fin, and Biron was
condemned and executed in 1602.
Bismarck of Asia.
Li Hung Chang, the Chinese statesman, was so called.
Black Act.
An Act passed in 1722 to put a stop to the depredations of certain
persons who frequented Epping Forest in disguise and killed the deer. The
Act was repealed in 1827.
Black Agnes.
Agnes, wife of the Earl of March, who was distinguished for her gallant
defence of Dunbar against the English in 1339.
Black Assize.
The assize held at Oxford in July, 1577, when an outbreak of typhus
fever carried off three hundred persons, including many of the officials and
jurors attending the court.
Black Bands.
A body of German soldiers enlisted by Louis XII of France, and
employed in the Italian wars of the sixteenth century.
Black Bartholomew.
St. Bartholomew’s Day, 1662, is so called. On this day all beneficed
clergy had to declare their assent to the Book of Common Prayer, in
accordance with the provisions of the Act of Uniformity, and those who
refused were deprived of their livings. Over two thousand Presbyterians
were ejected from their parishes on this day.
Black Book.
The name given to the report of the committee appointed by Henry VIII
in 1535 to investigate the condition of the monasteries.
Black Box.
A box said to have contained the marriage certificate of Charles II and
Lucy Waters, the mother of the Duke of Monmouth, and to have been stolen
from her. Had the documents it purported to contain been forthcoming, they
would, of course, have established the Duke’s right to the throne in the
place of James II.
Black Brunswickers.
A regiment of horse raised by the Duke of Brunswick in 1809, to avenge
the death of his father who was killed at Auerstadt. They wore black
uniforms, and their badge was the skull and crossbones.
Black Circuit.
A circuit held in Cape Colony in 1812 to investigate the charges brought
by the London Missionary Society against the Dutch settlers of ill-treating
their native slaves. The results showed that the charges were grossly
exaggerated, but a great deal of illfeeling was engendered amongst the
Dutch by the thoroughness with which the English Government went into
the matter.
Black Clergy.
The members of the regular monastic orders in Russia. They alone take
any part in the ecclesiastical administration.
Black Death.
A pestilence which passed over Europe, and finally reached England in
1349. Its ravages were terrible, amounting, according to some chroniclers,
to a third of the population. It probably had its origin in the East, and is
thought by some to have been the disease now known as the Bubonic
Plague.
Black Flags.
Rebel Chinese in the service of the King of Annam, who were the most
dangerous opponents of the French during the Tong-King war.
Black Friday.
May 11, 1866, on which day the failure of Overend and Gurney was
announced. There was a terrible panic in financial circles, and, among other
extraordinary measures, it was found necessary to suspend the Bank
Charter.
Black Hole of Calcutta.
The dungeon in which some 200 English prisoners were confined when
Calcutta was taken by Surabjah Dowlah, the Subahdar of Bengal, in 1756.
Only twenty-three survived the night.
Black Monday.
The name given to an Irish rising in County Dublin in 1209, which
nearly exterminated the newly-established English Colony.
Black Popes.
The chiefs of the Society of Jesus, during the Papacy of Pius IX, were
known by this name, their power in Rome being almost as great as that of
the Pope himself.
Black Prince.
The sobriquet of Edward, Prince of Wales, son of Edward III, from the
black armour which he habitually wore.
Black Rent.
An annual stipend paid by the English settlers within the Pale to the Irish
chieftains on their borders, in consideration of their restraining their
followers from raiding the English settlements. Black Rent was first paid
about 1410.
Black Watch.
A body of Highlanders, enrolled in 1725 for the purpose of maintaining
order in the Highlands. They were made a regular line regiment in 1739,
and numbered the 43rd. They later became the 42nd, and are now the Royal
Highlanders (Black Watch).
Black Wednesday.
See Victorian Deadlocks.
Blackbirders.
The name given to the vessels engaged in the Kanaka labour traffic in
the Southern Seas.
Blackburn Riots.
A series of disturbances by the Lancashire weavers, in 1826, as a protest
against the introduction of machinery. A large amount of damage was done
before the rioters were dispersed by the troops.
Blanche Nef.
The White Ship, in which Prince William, son of Henry I, was returning
to England, after the close of Henry’s second French war. The vessel struck
coming out of Barfleur harbour, and only one of the crew escaped.
Blancs d’Espagne.
The name given to the ultra-royalist party in France who support the
claim of the Spanish Bourbons, represented by General de Bourbon, to the
throne of France.
Bland Act.
An Act of Congress passed in 1878, at the instance of Mr. Bland,
providing for the coinage of silver dollars of 412½ grains Troy, which
should be legal tender in payment of all debts and dues. The State was
bound to purchase not more than four or less than two million dollars worth
of silver per annum, to be so coined, and the profit in the operation was to
belong to the State.
Blanketeers.
The name given to a party of Lancashire operatives, who, in the famine
year of 1817, started to march to London, to demand assistance from
Parliament. Each man carried provisions and a blanket, hence the name.
Blanquillos.
The supporters of Oribe in Uruguay, in 1835. Their opponents, who
followed Rivera, were called Colorados.
Bloc, Le.
The name given to the general body of Republicans, of various shades of
opinion, in the French Chamber, who supported the Ministry of M. Combes
in 1902-3.
Bloemfontein Conference.
A conference of delegates from Cape Colony, Natal, and the Orange Free
State, which met in 1895 to discuss the question of a Customs Union. Natal
could not come to terms, and withdrew, but an arrangement was arrived at
by the other two parties, and a convention tariff, with five per cent. ad
valorem duties, was accepted by both Governments.
Bloemfontein Convention.
A convention signed in 1854, by which the British Government
abolished the Orange River Sovereignty, and recognized the independence
of the Orange Free State. Among the provisions of the treaty were clauses
binding the British Government to make no treaties with native chiefs likely
to be detrimental to the interests of the Republic, forbidding slavery, and
providing for extradition.
Blood Council.
A tribunal established in 1567 by Alva in the Netherlands, to deal with
the crime of treason. It had no charter, or official authority of any kind, but
it practically usurped the functions of the Council of State, and exercised
jurisdiction over all municipal bodies and provincial parliaments. It was
abolished in 1576. It was also known as the Council of Troubles.
Blood Tax.
The sixteenth section of the Crimes Act of 1882, by which it was
proposed to levy compensation for murder or maiming on the ratepayers of
the district where the crime was committed, was so called by the Irish
members.
Blood-red Wedding.
See Noces Vermeilles.
Blood-wite.
Another name for Were-gild.
Bloody Assizes.
The Assizes held by Jeffreys on the Western Circuit, shortly after the
suppression of Monmouth’s rebellion in 1686. Hundreds of Monmouth’s
adherents were sent to the scaffold, or transported as slaves to the West
Indies.
Bloody Statute.
The Act of the Six Articles, passed in the reign of Henry VIII, was so
called.
Blue-Grass State.
A name sometimes given to the State of Kentucky, U.S.A., which
contains the famous blue grass region, celebrated for the raising of horses.
Board of Control.
The board established by Pitt’s India Act in 1784 to supervise the
Government of India by the East India Company.
Bobbing John.
The sobriquet of the Earl of Mar, the Jacobite leader in the rebellion of
1815. He was a notorious trimmer.
Bocca di Leone.
The name given to the opening in the wall of the antechamber in the
Doge’s Palace at Venice, into which anonymous accusations were dropped.
Bocland.
In Saxon times, land held by grant or by charter from the public lands.
Body of Liberties.
The first constitution of Massachusetts, prepared by Nathaniel Ward. It
provided that all public officials should be chosen annually by the freemen
of the plantation. Each town also elected deputies to a general assembly, to
serve for one year. Each town had the right to make its own by bye-laws. It
further provided for the annual election of judges, and for equal justice to
all, including foreigners, while severe penalties were enacted for witchcraft
and blasphemy.
Bomba.
The sobriquet of Ferdinand II, King of the Two Sicilies (1759-1825).
Bonaght.
See Coyne and Livery.
Bond.
See Afrikander.
Bond-Blaine Convention.
An agreement between Newfoundland and the United States, signed in
1890, providing for the continuance of the modus vivendi affording
reciprocal fishing rights to the two countries.
Bondevenner.
The Peasants’ Friends, a political party formed in Denmark in 1845, in
the interests of the rural population.
Bondi.
In Norse times, the freeholders or owners of Odal land.
Book of Rates.
A table of unauthorized import duties issued by Cecil, Earl of Salisbury,
in 1608, after the decision in the Crown’s favour in Bates’ case. In 1610 the
Commons declared these impositions illegal.
Book of Sports.
A declaration of James I in 1618, as to the sports which might lawfully
be indulged in on Sundays after Divine Service. Dancing, archery,
maypoles, leaping were permitted; bear-baiting was forbidden. None,
however, might take part unless they had been to church.
Booth’s Conspiracy.
A conspiracy headed by John Wilkes Booth, at the end of the American
Civil War, having for its object the assassination of the President, Vice-
President, and some others. President Lincoln was shot by Booth on April
14, 1865, and on the same date Seward, the Secretary of State, was
wounded by Payne, another of the conspirators. The conspirators were
brought to trial, and four of them hanged, the others being sentenced to
various terms of imprisonment.
Border Laws.
A code of laws framed in 1249 by a commission composed of twelve
English and twelve Scottish knights. They dealt with the surrender of
fugitives crossing the border, and provided for the trial of border raiders by
special courts, held under the joint authority of the two nations.
Border States.
Before the American Civil War, this name was applied to the States
bordering on the free states, namely, Delaware, Maryland, Virginia,
Kentucky, and Missouri.
Boston Massacre.
A small affray in Boston in 1770, in which the troops fired on the rioters,
and a few persons were killed. Captain Preston, who commanded the
troops, was tried and acquitted.
Boston Port Act.
An Act passed in 1774, closing the Custom House and Port of Boston. It
was passed as a measure of retaliation for the action of the inhabitants in
preventing the importation of tea by the East India Company free of the
English duty.
Botany Bay.
A small inlet in the coast of New South Wales, where the first convict
establishment was formed in 1787. The penal settlement was removed to
Port Jackson in the following year, but the name was constantly used,
generically, for the convict settlements in Australia.
Boulangists.
The supporters of General Boulanger, who obtained a brief popularity in
France in 1886, largely owing to the army reforms he introduced while
Minister of War. He gradually, however, attracted to his standard the
reactionary parties, who hoped that he would destroy Parliamentary
Government. He quickly obtained a large following in the country, rather by
denunciation of Parliamentary abuses than by the advocacy of any definite
policy, and in 1888 he was elected for three Departments. At this period he
might have overturned the Government, but shrank from the decisive step,
and from that time his influence began to wane. He left France to escape
prosecution, and his following quickly dwindled away, until in 1890, it was
found desirable to dissolve the Boulangist committee. Boulanger committed
suicide in Brussels in 1891.
Boustrapa.
A nickname of Napoleon III, compounded of the first syllables of
Boulogne, Strasbourg, and Paris, the scenes of his two unsuccessful and one
successful coups d’état, in 1840, 1836, and 1851 respectively.
Boxers.
A Chinese Secret Society, whose principal object is the expulsion from
China of Europeans, and especially of missionaries. They have met with
considerable sympathy in Court circles, and their outrages in 1900 led to a
joint European expedition. Their rising was suppressed for a time, but the
agitation is seething, and may break out again at any time.
Boy Popes.
This title is given to John XII, who was elected Pope in 956, at the age
of eighteen, and Benedict IX, who was Pope from 1033 to 1044, having
been chosen at the age of ten.
Boyars.
In early Russian history, the large landowners, under the authority of the
great princes who ruled the various Principalities into which Russia was
divided.
Boycotting.
One of the weapons employed by the Irish Land League, in its campaign
against the landlords. It consists in ostracizing the person aimed at, and
forbidding any one to deal with or work for him, or supply his wants. Its
first victim was Captain Boycott, the agent of the Earl of Erne in 1880, and
from his name the word is derived.
Boys.
The name given by Walpole to the party of young Whigs, under William
Pitt, who acted with the “Patriots” in 1733.
Braemar Gathering.
See Hunting of Braemar.
Brahmins.
The highest or priestly caste among the Hindus.
Brahmo Somaj.
A Hindu sect, founded in 1830 by Rammohun Roy. Its tenets are
monotheistic, rejecting the numerous gods of the Hindu Pantheon, and
adoring Brahma as the supreme deity. Its adherents ignore all caste
distinctions.
Brandy Nan.
Queen Anne was so called by the Londoners.
Bras de Fer.
The sobriquet of Baldwin, first Count of Flanders.
Bread Riots.
A series of disturbances in various parts of England, in 1816, caused by
the high prices of food-stuffs, due to the bad harvest and the cessation of the
Great War. In many places it was necessary to call out the military to
disperse the rioters.
Brehon Law.
The Irish Law which prevailed throughout Ireland after the conquest by
Henry II, excepting within the Pale. It was abolished in the reign of James I.
Breton Club.
A revolutionary club formed in Paris in the early days of the Revolution.
Its founders were certain Breton deputies, and among its members were
many who were afterwards prominent Jacobins, amongst others
Robespierre.
Bretwalda.
Under the Saxon Heptarchy, the sovereign of one of the seven kingdoms
was often acknowledged as the leader of the Federation, under the title of
Bretwalda.
Brewer of Ghent.
James van Arteveldt, the leader of the Burgher party in Flanders in 1338,
was so called.
Bridal of Norwich.
A conspiracy against William I, entered into at the bridal feast of Ralph
of Gwader, Earl of Norfolk, and Emma, sister of the Earl of Hereford. The
two earls, with Waltheof, Earl of Nottingham, designed to depose William
and divide the kingdom between them. Waltheof seems to have repented,
and confessed the plot to Lanfranc. The conspiracy was at once suppressed,
Waltheof executed, and Hereford imprisoned for life, while Ralph escaped
to Brittany.
Brig-bot.
In Anglo-Saxon times, a tax levied on freemen for the repair of bridges.
Bright Clauses.
The clauses in the Irish Land Act of 1870, dealing with the sale of land
to tenants are so called, John Bright having for many years advocated State
aid in the creation of a peasant proprietary in Ireland.
Brilliant Madman.
Charles XII of Sweden is so called.
Brissotins.
The followers of Brissot, one of the leaders of the Gironde, during the
French Revolution. The name fell into disuse, as the party became merged
in the Girondins.
Bristol Riots.
A riot in Bristol in 1831, consequent upon the rejection of the Reform
Bill by the House of Lords. The Recorder of Bristol, Sir Charles Wetherell,
was mobbed on his entrance into the city, and the rioters seized the town
hall. The weakness of the authorities left the disorder unchecked for two
days, but at the last the military were called out and the disturbance
suppressed.
Broad-bottomed Administration.
Pelham’s Ministry as reconstructed in 1744 was so called, because it
contained members representing every shade of Whig opinion, and even a
certain admixture of Toryism.
Brömsebro, Treaty of.
A treaty between Sweden and Denmark, signed in 1645, by which
Denmark surrendered Jämtland, Hejealand and Halland, and granted to
Swedish vessels exemption from the payment of Sound Dues.
Brother Jonathan.
The nickname of the American nation.
Brownists.
A dissenting sect, who seceded from the Church in 1582. They objected
to general church government, and claimed for each congregation the right
to regulate its own worship. They may be considered the forerunners of the
Independents.
Buccaneers.
An association of sea-rovers formed about 1525, to harry the Spanish
possessions in South America, and prey upon their commerce. They were of
various nationalities, but chiefly English and French, and their most famous
leaders were Montbars, known as the Exterminator, and Henry Morgan,
afterwards Sir Henry, and Deputy-Governor of Jamaica. Under the latter
leader they crossed the Isthmus and sacked the city of Panama in 1671, and
for years they paralyzed the Spanish trade, both in the Caribbean Sea and in
the Pacific. They ceased to exist as an association early in the eighteenth
century, but some of them continued a career of indiscriminate piracy for
many years longer. They were called by the French Flibustiers.
Buckeye State.
The popular name of the State of Ohio, U.S.A., from the number of
buckeye-trees found within its borders.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com