100% found this document useful (2 votes)
10 views

Mastering JavaScript Single Page Application Development 1. Edition Klauzinski download

The document is a promotional material for the book 'Mastering JavaScript Single Page Application Development' by Philip Klauzinski and John Moore, detailing its content and structure. It covers various aspects of building sophisticated single-page applications using JavaScript, including design, architecture, and essential techniques. Additionally, it provides links to other related eBooks and resources available for download.

Uploaded by

sassesalhigp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
10 views

Mastering JavaScript Single Page Application Development 1. Edition Klauzinski download

The document is a promotional material for the book 'Mastering JavaScript Single Page Application Development' by Philip Klauzinski and John Moore, detailing its content and structure. It covers various aspects of building sophisticated single-page applications using JavaScript, including design, architecture, and essential techniques. Additionally, it provides links to other related eBooks and resources available for download.

Uploaded by

sassesalhigp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Mastering JavaScript Single Page Application

Development 1. Edition Klauzinski download

https://ebookname.com/product/mastering-javascript-single-page-
application-development-1-edition-klauzinski/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Beginning Windows Store Application Development HTML


and JavaScript Edition Burns

https://ebookname.com/product/beginning-windows-store-
application-development-html-and-javascript-edition-burns/

Beginning iOS Application Development with HTML and


JavaScript 1st Edition Richard Wagner

https://ebookname.com/product/beginning-ios-application-
development-with-html-and-javascript-1st-edition-richard-
wagner-2/

Beginning iOS Application Development with HTML and


JavaScript 1st Edition Richard Wagner

https://ebookname.com/product/beginning-ios-application-
development-with-html-and-javascript-1st-edition-richard-wagner/

Mapping the Invisible The Informal Food Economy of Cape


Town South Africa 1st Edition Jane Battersby

https://ebookname.com/product/mapping-the-invisible-the-informal-
food-economy-of-cape-town-south-africa-1st-edition-jane-
battersby/
Discrete Variational Derivative Method A Structure
Preserving Numerical Method for Partial Differential
Equations 1st Edition Daisuke Furihata

https://ebookname.com/product/discrete-variational-derivative-
method-a-structure-preserving-numerical-method-for-partial-
differential-equations-1st-edition-daisuke-furihata/

Blender for Animation and Film Based Production 1st


Edition Michelangelo Manrique

https://ebookname.com/product/blender-for-animation-and-film-
based-production-1st-edition-michelangelo-manrique/

Macromolecules Containing Metal and Metal Like Elements


Biomedical Applications Macromolecules Containing Metal
and Metal like Elements 1st Edition Alaa S. Abd-El-Aziz
Charles E. Carraher Charles U. Pittman John E. Sheats
Martel Zeldin
https://ebookname.com/product/macromolecules-containing-metal-
and-metal-like-elements-biomedical-applications-macromolecules-
containing-metal-and-metal-like-elements-1st-edition-alaa-s-abd-
el-aziz-charles-e-carraher-charles-u-p/

The Ultimate Sourcebook of Knitting and Crochet


Stitches 1st Edition Harmony Guides

https://ebookname.com/product/the-ultimate-sourcebook-of-
knitting-and-crochet-stitches-1st-edition-harmony-guides/

Pioneering Stem Cell Gene Therapy Trials 1st Edition


Roger Bertolotti (Author)

https://ebookname.com/product/pioneering-stem-cell-gene-therapy-
trials-1st-edition-roger-bertolotti-author/
Securing the World Economy The Reinvention of the
League of Nations 1920 1946 1st Edition Patricia P.
Clavin

https://ebookname.com/product/securing-the-world-economy-the-
reinvention-of-the-league-of-nations-1920-1946-1st-edition-
patricia-p-clavin/
Mastering JavaScript Single
Page Application Development

An in-depth guide to exploring the design, architecture, and


techniques behind building sophisticated, scalable, and
maintainable single-page applications in JavaScript

Philip Klauzinski
John Moore

BIRMINGHAM - MUMBAI
Mastering JavaScript Single Page
Application Development
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 authors, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be caused
directly or indirectly by this book.

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

First published: October 2016

Production reference: 1241016

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78588-164-0
www.packtpub.com
Credits

Authors Copy Editor

Philip Klauzinski Safis Editing


John Moore

Reviewers Project Coordinator

Ciro Artigot Ritika Manoj

Commissioning Editor Proofreader

Wilson D'souza Safis Editing

Acquisition Editor Indexer

Reshma Raman Rekha Nair

Content Development Editor Graphics

Divij Kotian Jason Monteiro

Technical Editor Production Coordinator

Sachit Bedi Aparna Bhagat


About the Authors
Philip Klauzinski is a senior frontend developer specializing in JavaScript Single Page
Application (SPA) development. He has over 20 years of experience in web design and web
development and is a leading expert in web application development, client-side JavaScript,
and Search Engine Optimization (SEO). Philip has worked as a frontend developer across
multiple industries, including consumer e-commerce, business-to-business e-commerce, big
data, Web hosting, direct marketing, domain name services (DNS), and manufacturing.

I would like to thank my Mom and Dad for always stressing the importance of education in
my life, not just institutional education, but more importantly, the pursuance of self-
education. My own interest in technology and software from a young age has driven my
subsequent, self-taught approach to my career. As a result, I love what I do for a living,
and I have been able to shape my professional life around the things in which I am truly
interested. I am inherently driven to learn more every day, and I believe that is what has
led to my success. Thank you, Mom and Dad!

John Moore has been working in web development for 20 years. He is an industry expert in
JavaScript and HTML5. He has developed award-winning web applications and worked
and consulted for Digital Equipment Corporation, Ernst & Young, Wachovia Bank, and
Fidelity Investments. Having focused his early career on frontend web development, he
helped usher in responsive web design and Single Page Applications in his roles in
development and architecture. Most recently, he led Full Stack development in JavaScript,
serving as CTO of a Maine-based startup company.

I would like to thank my wife, Dr. Myra Salapare, and daughters, Mila Moore and Sophia
Moore, for all of their support. I would also like to thank Andrea Shiflet, Erin Benner, and
Lauren Grousd for their tremendous help.
About the Reviewer
Ciro Artigot is currently working as an IT manager at ECODES, an Spanish foundation that
works for the welfare of all people within the limits of our planet.

He has developed websites for over 15 years. He is a Full Stack developer and CMS expert
and is addicted to Joomla, He has worked for 10 years in open source GNU projects, mainly
in LAMP .

For the last few years, he has been investigating and working with SPA in MEAN
environments.

I would like to thank Pampa, Diego,and Hugo, for giving me the time to review this book,
and my parents and brothers, for making it possible for me to devote myself to what I like
best—develop
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at service@packtpub.com 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://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Table of Contents
Preface 1
Chapter 1: Getting Organized with NPM, Bower, and Grunt 7
What is Node Package Manager? 8
Installing Node.js and NPM 8
Configuring your package.json file 9
NPM dependencies 10
Updating your development dependencies 11
Bower 11
Installing Bower 12
Configuring your bower.json file 12
Bower components location and the .bowerrc file 14
Bower dependencies 14
Searching the Bower registry 15
Grunt 16
Installing the Grunt CLI 17
Installing the Grunt task runner 17
Installing Grunt plugins 17
Configuring Grunt 19
Understanding Node.js modules 19
Creating a Gruntfile 20
Defining Grunt task configuration 21
Loading Grunt plugins 22
Running the jshint Grunt task 24
Running the watch Grunt task 25
Defining the default Grunt task 27
Defining custom tasks 27
Summary 29
Chapter 2: Model-View-Whatever 30
The original MVC pattern 30
The Model 31
The View 32
The Controller 33
MVP and MVVM 34
MVP 34
MVVM 35
Summarizing the differences between MVC, MVP, and MVVM 36
VIPER and other variations of MVW 36
VIPER 36
Other variations of MVW 37
AngularJS and MVW 38
A brief history of AngularJS 38
AngularJS components 39
Template 39
Directives 39
Model 40
Scope 40
Expressions 40
Compiler 41
Filter 41
View 41
Data binding 41
Controller 42
Dependency injection 42
Injector 43
Module 43
Service 43
Using the MVW pattern in an SPA 44
Building a simple JavaScript SPA 44
Creating the Model 45
Creating the View 45
Setting up frontend assets 46
Compiling web templates 46
Precompiling web templates 46
Handling server HTTP requests 47
Creating the SPA layout 47
Serving the SPA 48
Overview of a simple JavaScript SPA 49
Summary 50
Chapter 3: SPA Essentials – Creating the Ideal Application Environment 51
The JSON data format 51
Other data formats 53
XML 53
YAML 54
BSON 54
Why does JSON reign supreme? 55
The differences between SQL and NoSQL databases 55
NoSQL data typing 56
Relational data typing 56
ACID transactions 57
Atomicity 57

[ ii ]
Consistency 57
Isolation 58
Durability 58
MongoDB and ACID 58
Write-ahead logging with MongoDB 58
When to use SQL versus NoSQL databases 59
Scalability 59
Horizontal scaling 59
Big Data 59
Operational Big Data 60
Analytical Big Data 60
Overall considerations 61
Methods of presenting an SPA container 61
How to define your SPA container 62
Partial page container 62
Full page container 62
How to load your SPA container 63
Loading on user interaction 63
Login page transition 63
Loading based on the DOMContentLoaded event 64
Loading based on the document readystatechange event 65
Loading directly from the document.body 65
Using the script tag async attribute 67
Using the script tag defer attribute 67
Managing layouts 68
Static layouts 68
Dynamic layouts 69
Installing Express 69
Setting up a basic server with Express 70
Basic routing with Express 70
Running a server with Express 71
Loading static assets with Express 71
Dynamic routing with Express 72
Summary 73
Chapter 4: REST is Best – Interacting with the Server Side of Your App 74
Understanding the fundamentals of REST 75
Understanding an architectural style versus a protocol 75
Architectural style 75
Protocol 76
Transport layer protocols 76
Application layer protocols 76
Using HTTP as a transfer protocol for REST 77
The constraints of REST 78
Client-server 78

[ iii ]
Stateless 78
Cache 79
Uniform interface 80
Identification of resources 80
Manipulation of resources through representations 81
Self-descriptive messages 81
Hypermedia as the engine of application state 81
Layered system 81
Code-on-demand 82
Benefits of REST 83
Performance 83
Simplicity 84
Separation of concerns 84
Scalability 84
Portability 84
Visibility 85
Reliability 85
RESTful web services 85
Setting up a simple database with MongoDB 86
Installing MongoDB 86
Installing MongoDB on Mac using Homebrew 86
Creating a MongoDB data directory 87
Running MongoDB 87
Creating a collection with MongoDB 87
Installing the Node.js MongoDB driver 88
Writing basic REST API endpoints 89
CRUD with REST 89
Handling request data with Node.js and Express 90
Creating with a POST request 90
Testing the POST request on the frontend 92
Reading with a GET request 93
Testing the GET request on the frontend 94
Updating with a PUT request 96
Testing the PUT request on the frontend 97
Deleting with a DELETE request 99
Testing the DELETE request on the frontend 100
Alternatives to REST 101
TCP versus UDP 101
SOAP 103
WebSockets 104
MQTT 105
AMQP 106
CoAP 107
DDP 108

[ iv ]
Summary 109
Chapter 5: Its All About the View 110
JavaScript templating engines 110
Underscore.js 111
Mustache.js 112
Sections 113
Boolean values 113
Lists 114
Lambdas 115
Inverted sections 115
Comments 116
Partials 117
Set alternative delimiters 118
Handlebars.js 119
Explicit path lookup versus recursive path lookup 119
Helpers 121
Helpers as block expressions 122
#if block helper 122
#unless block helper 123
#each block helper 123
#with block helper 124
Other differences in Handlebars from Mustache templates 125
Precompiling templates 125
No alternative delimiters 125
Pure.js 126
Markup 126
Pug 127
Embedded JavaScript (EJS) 129
Synchronous template loading 130
Asynchronous data loading 131
Caching 131
View helpers 131
The link_to view helper 132
The img_tag view helper 132
The form_tag view helper 132
Partials 133
Optimizing your application layout 134
UglifyJS and grunt-contrib-uglify 134
grunt-contrib-handlebars 136
Options configuration 137
Files configuration 138

[v]
Running the Grunt Handlebars task 138
Watching for changes 139
Putting it all together 142
Summary 142
Chapter 6: Data Binding, and Why You Should Embrace It 143
What is data binding? 143
One-way data binding 144
Two-way data binding 145
Data binding with modern JavaScript frameworks 146
Data binding with AngularJS 146
One-way data binding with AngularJS 146
Two-way data binding with AngularJS 147
Dirty checking with AngularJS 148
Dirty checking by reference 149
Dirty checking by collection contents 150
Dirty checking by value 150
When to use dirty checking for data binding 151
Data binding with Ember.js 151
Computed properties 152
One-way data binding with Ember.js 153
Two-way data binding with Ember.js 153
Data binding with Rivets.js 154
One-way data binding with Rivets.js 155
Defining your own one-way binder 156
Two-way data binding with Rivets.js 157
Defining your own two-way binder 157
Implementing data binding with native JavaScript 158
Object getters and setters 158
The object initializer 159
The Object.defineProperty() method 159
Designing a getter and setter data binding pattern 160
Synchronizing data in the View 161
Abstracting the design pattern to a reusable method 162
Accounting for DOM mutations 164
MutationObserver 164
Extending dataBind with MutationObserver 166
Why use data binding? 169
Use cases for one-way data binding 169
Use cases for two-way data binding 170
Summary 170
Chapter 7: Leveraging the MEAN Stack 171
The Node.js environment 172

[ vi ]
Running the REPL 172
Writing a hello Node.js script 173
Setting up a Node.js project with NPM 174
Getting started with Express 176
Installing Express 176
Standard method 177
Express generator 177
Setting up your Express application 178
Exploring the main script 179
Looking at the main application 180
Loading dependencies 180
Configuring the application 180
Application-level middleware 181
Our first Express route 181
Rendering the first view 182
Exploring MongoDB 183
Setting up MongoDB 183
Working with the MongoDB shell 184
Selecting a database 184
Inserting documents 185
Finding documents 185
Updating documents 186
Removing documents 187
Create your SPA database 188
Starting with AngularJS 189
Installing AngularJS into the application 189
Building the first AngularJS module 191
Adding a controller 192
Displaying data with Angular expressions 194
Two-way data binding 195
Summary 196
Chapter 8: Managing Data Using MongoDB 197
Exploring the NoSQL database model 197
Defining NoSQL 198
NoSQL 198
Non-relational 198
Distributed 198
Features of MongoDB 199
Document model 199
Schemaless 200
Open source 200
Why use MongoDB? 200

[ vii ]
Well supported 200
Data model 201
Popularity 201
Commanding MongoDB 202
Getting information 202
Inserting and updating data 203
Running scripts in the MongoDB shell 204
Running bulk operations 206
Finding, modifying, and removing data 208
Specific results 208
Query operators 209
Projections 210
Query modifiers 211
Modifying data 212
Removing data 215
The cursor 217
Incorporating MongoDB into the SPA 218
Adding the NPM modules 218
Adding MongoDB into the main application 218
Writing a query 220
Displaying data in a page 222
MongoDB database performance 224
Indexing 224
Optimizing queries 225
Using limit 226
Using projections 226
Using hint() 227
Analyzing performance 228
Summary 230
Chapter 9: Handling Web Requests with Express 231
Examining Express in detail 232
App object 232
app.locals 234
app.set() 236
app.enable() 237
app.disable() 237
app.listen() 237
app.METHOD() 238
app.all() 239
Request object 239
req.params 240
req.body 243
req.query 244

[ viii ]
req.cookies 244
req.xhr 245
req.accepts() 246
req.get() 246
Response object 246
res.app 246
res.cookie() 247
res.download() 247
res.json() 248
res.jsonp() 248
res.redirect() 248
res.render() 249
res.send() 250
Router object 251
router.METHOD() 253
router.all() 254
router.param() 254
Writing our own middleware 256
Developing a RESTful API 259
Installing resourceful routing 260
Building out giftlist controller 262
Responding with different data formats 263
Summary 266
Chapter 10: Displaying Views 267
Setting up our dashboard 268
Building the view 268
Connecting to initial data 273
Implementing Bootstrap 277
Implementing AngularJS 281
Our AngularJS module 282
Controlling state with UI-router 284
AngularJS controllers 288
Talking to the backend 292
Creating an AngularJS factory 293
Using AngularJS $resource 294
Summary 297
Chapter 11: Adding Security and Authentication 298
Adding authentication with Passport 299
Installing Passport 299
Using Mongoose to configure the database 302
Installing and configuring Mongoose 302
Creating the user model 305

[ ix ]
Setting up Passport strategies 306
Initializing Passport 306
Creating the signup strategy 309
Creating the login strategy 311
Creating routes for authentication 313
Creating views for authentication 317
Authenticating requests 322
Adding authentication-check middleware 322
Inserting middleware into routes 323
Changing the dashboard route 324
Securing Express 325
Helmet 325
CSRF 329
Taking additional security measures 332
Implementing HTTPS 332
Avoiding running as root 332
Validating user input 333
Summary 333
Chapter 12: Connecting the App to Social Media 334
Connecting to Facebook 334
Setting up your Facebook developer account and app 334
Setting up the Passport strategy 338
Configuring for Facebook 338
Setting up the routes for Facebook authentication 339
Finishing setting up the Passport strategy 340
Altering the User model for Facebook data 342
Finishing the connection to Facebook 342
Recreating our home page 343
Connecting to Twitter 345
Adding a Twitter app 346
Setting up our Twitter strategy 347
Adding Twitter authorization to our home page 351
Sharing giftlists 353
Fleshing out the giftlist model 353
Connecting the UI 354
Connecting the form 356
Creating the controller 356
Angularizing the form 357
Connecting to the backend controller 358
Adding the ability to share lists on social media 361
Summary 364

[x]
Chapter 13: Testing with Mocha, Karma, and More 365
Types of testing 365
Unit testing 366
Mocha 367
Assertions with Chai 368
Running Mocha tests in the browser 371
Sinon.js 373
Spies 373
Stubs 374
Mocks 375
Jasmine 376
Karma test runner 376
Testing with Karma, Mocha, and Chai 376
Testing AngularJS with Karma and Jasmine 379
Integration testing 382
End-to-end testing 382
The angular-seed project 382
End-to-end testing with AngularJS and angular-seed 384
Summary 389
Chapter 14: Deploying and Scaling the SPA 390
Packaging for deployment 391
Setting up Grunt for deployment 391
Installing Grunt 391
Installing Grunt plugins 392
Configuring the Gruntfile 393
Running Grunt 396
Setting up our config for production 397
Create a .gitignore file 398
Create an environment-based configuration module 398
Using the new config file 399
Setting up a cloud database 404
Creating a MongoLab account 405
Creating a database 405
Setting up a user to access the database 407
Deploying the application to Heroku 408
Getting ready to use Heroku 408
Setting up Git 408
Signing up for a Heroku account 409
Installing the HerokuToolbelt 409
Setting up the Heroku project 410
Deploying to Heroku 410
Defining a Procfile 410
App environment variables 411

[ xi ]
Deploying 412
Scaling the SPA 414
Scaling the database 414
Scaling the server 414
Summary 415
Index 416

[ xii ]
Preface
Created in 1995 by Brendan Eich of Netscape, JavaScript has gone from being a toy scripting
language used only in browsers to being one of the most popular languages in the world for
full-stack development. With the introduction of Node.js, built on top of Chrome’s V8
JavaScript Engine, developers are now able to build powerful and performant applications
using JavaScript. With the addition of MongoDB, a modern NoSQL database, applications
can utilize JavaScript at every tier.

Many popular web applications are implemented, partially or in whole, as single-page


applications, or SPAs. With SPAs, users load a single web page, and that page is updated
dynamically in response to user interaction or incoming server data. The advantage is an
application experience that is smoother, replicates native application interaction, and may
require less network traffic and server load.

The MEAN stack is a set of JavaScript tools representing a full stack, from database to
runtime environment, application framework, and frontend. This book provides a thorough
background in building SPAs using the MEAN stack and other tools in the JavaScript
ecosystem. It covers the basics of SPA architecture and JavaScript tools. The book then
expands to more advanced topics, such as building, securing, and deploying an SPA built
with the MEAN stack.

What this book covers


Chapter 1, Getting Organized NPM, Bower, and Grunt, introduces JavaScript frontend
package-management, build, and task-running tools. These tools form the foundation for
you to set up an ideal development environment.

Chapter 2, Model-View-Whatever, goes beyond the original MVC design pattern and
explores its translation into frontend frameworks and its evolution into Model-View-*, or
Model-View-Whatever (MVW), in which the Controller layer is more open ended and often
abstracted into other layers more suited to an SPA environment.

Chapter 3, SPA Essentials - Creating the Ideal Application Environment, introduces you to the
common components/layers of an SPA, the best practices and variations around these
components, and how to put them together and lay the groundwork for a modern SPA.
Preface

Chapter 4, REST is Best - Interacting with the Server Side of Your Application, goes into further
detail about the server side of SPA architecture—in particular, with regard to the REST
(representational state transfer) architectural pattern. You’ll become familiar with different
methods to interact with a REST API using JavaScript and AJAX, with practical examples.

Chapter 5, Its All About the View, focuses on the concept of views in the SPA architecture
and how views can be initialized in a single-page container. It discusses JavaScript
templates and provides examples from different libraries, going deeper into how AngularJS
views are implemented.

Chapter 6, Data Binding, and Why You Should Embrace It, teaches you about data binding,
describes one-way versus two-way data binding, and discusses the practicality of data
binding in an SPA and why you should use it. You will also cover the continual evolution of
the ECMAScript/JavaScript standard and how it now supports native data binding in some
clients.

Chapter 7, Leveraging the MEAN Stack, introduces you to the MEAN stack (MongoDB,
Express, AngularJS, and Node.js) and how they work together. You will install and
configure MongoDB and Node.js and explore working with each on the command line.
You’ll create a database for a new SPA and learn about AngularJS and Express, the two
other pieces of the stack.

Chapter 8, Manage Data Using MongoDB, teaches you how to create and manage databases
in MongoDB. Using the command line, you will execute CRUD (create, read, update, and
delete) functions.

Chapter 9, Handling Web Requests with Express, familiarizes you with the Express routing
middleware and handling requests from and responses to the browser. After configuring
the Express router, you’ll create a number of routes, which return dynamically generated
data to the web browser when requested, organize your routes logically, and handle POST
requests from forms.

Chapter 10, Displaying Views, explores combining dynamic view rendering in Express along
with AngularJS. You will configure the Express application to use EJS (Embedded
JavaScript) templates and use Bootstrap for basic styling.

Chapter 11, Adding Security and Authentication, teaches you how to secure the Express-
based SPA by preventing common exploits such as cross-site request forgery (CSRF). You
will install passport-authentication middleware for Node.js and configure it for local
authentication and set up session management.

[2]
Preface

Chapter 12, Connecting the App to Social Media, extends the SPA by connecting it to multiple
social media platforms. You will set up passport authentication using Facebook and Twitter
strategies and share data from the SPA.

Chapter 13, Testing with Mocha, Karma, and More, teaches you testing, both on the server
side and in the view.

Chapter 14, Deploying and Scaling the SPA, walks you through setting up a production
database on MongoLab and deploying your SPA to Heroku. Finally, you will explore
scaling your SPA in the cloud.

What you need for this book


The book requires very few pieces of software besides your web browser and your
operating system's command line or terminal. You will need an editor for writing code. Any
text editor will do, from Notepad to an IDE such as Jetbrains WebStorm.

Who this book is for


This book is ideal for JavaScript developers who want to build complex SPAs in JavaScript.
Some basic understanding of SPA concepts will be helpful but are not essential.

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, path
names, dummy URLs, user input, and Twitter handles are shown as follows: "We can
include other contexts through the use of the include directive."

A block of code is set as follows:


module.exports = function(grunt) {

grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),

[3]
Preface

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['dist/**'],
copy: {
main: {
files: [

Any command-line input or output is written as follows:


$ npm install -g grunt-cli
grunt-cli@0.1.13 /usr/local/lib/node_modules/grunt-cli
├── resolve@0.3.1
├── nopt@1.0.10 (abbrev@1.0.7)
└── findup-sync@0.1.3 (lodash@2.4.2, glob@3.2.11)

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: "Clicking the Next button
moves you to the next screen."

Warnings or important notes appear in a box like this.

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.

[4]
Preface

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.p
acktpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.c
om/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

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/PacktPubl
ishing/Mastering-JavaScript-Single-Page-Application-Development. We also have
other code bundles from our rich catalog of books and videos available at https://github.
com/PacktPublishing/. Check them out!

[5]
Preface

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/conten


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

[6]
Exploring the Variety of Random
Documents with Different Content
I remember also with pleasure, the family of Mr. S—, the English
Consul at Brussa, in whose house we dined, in company with his
daughter and son-in-law, the Consul of Bucharest. That evening,
while we talked in the drawing-room of Turner and Landseer, Ruskin
and Tennyson, I would almost think myself in a London drawing-
room. But at that moment I turned round to the open window, and
saw the stars shining with Eastern splendour, and then I
remembered where I was.
I was quite sad when I took leave of M. and Mme. S— and their
daughters; but sorrows and joys pass quickly on a journey. When I
had mounted Mme. S—’s charming little horse she kindly lent me,
and was cantering along on our way to Gimlek, where we were to
find a boat to take us back to Constantinople, I felt all my spirits
return. We accomplished that journey, which usually takes six hours,
in four, although we rested twice, at a little kind of caravansery, and
had coffee.
Soon after our return from Brussa we left Constantinople, and, if
that only is well which ends well, Constantinople was not well, for
going on board the French steamer, which was to take us to
Messina, was even less agreeable than our embarkation at Rettimo
had been. I wished to make a few trifling purchases on my way
down to the embarcadair, and my husband therefore proposed to
take our luggage to the custom-house, and see it safely on board,
while I should join him under the escort of the dragoman. When I
got into the boat I much regretted having quitted my husband, for
the day being windy and squally, I found the sea very rough. The
steamboat was far out, and the waves so high, that the spray quite
wetted me, and I had not the warm hand of my husband, but only
the cold wet board of the boat to cling to. I was frightened. Still this
was nothing to the terror I felt, when at last safely on board the
vessel I found that the luggage had arrived, but not my husband.
When he saw that the sea was rough, and knowing that I am of a
timid disposition, he had sent on the luggage, thinking he would try
to find me and take me on board himself. When I heard this I was
nearly in despair, however ridiculous this may seem now. There was
I in the steamboat, and my husband still on shore. With the strong
current and sea, the boat took much longer time than usual. Might
the steamboat not take me to Messina and leave him behind? Would
he not, when he found I was gone, take one of those nutshells of a
Kaik instead of another boat, and be drowned? for the Kaiks are very
dangerous in rough weather. He soon arrived, however, safely in a
boat, and I, immensely relieved, but cold and wet and shivering,
went down into my cabin to change my wet things. While there I felt
the machine begin to work and the boat slowly moving. I hastened
on deck. We were just turning round the Seraglio Point, and even
under the cold threatening sky that hung over the town, it was a
glorious sight. But I turned away from it without regret. It had
interested, but not attracted me. I did not wish for a palace on the
Bosphorus, as I had wished for a castle on the Rhine, or a villa on
the Bay of Naples. Indeed, I think I would rather live in a little
cottage in an English village, than inhabit one of the dreary palaces
of Stamboul.
CHAPTER IV.
FROM CONSTANTINOPLE TO FLORENCE.

“Land of the Sun! where’er my footsteps roam,


My thoughts return to thee—thou art my spirit’s home.”
J. H. Pringle.

And thus the days of Constantinople had gone by, and we were on
our voyage back, westward ho! The ship had spread its sails, and
the fresh north wind sped us on our way. The sea was very rough;
but the movement of the ship, going with the wind, was not
unpleasant.
The second night of our voyage I slept very soundly; the waves
had rocked me to sleep. Suddenly I was roused by cannon shots,
which appeared to be fired-off close to my cabin-window, and shook
our vessel. I rose quickly, and found that we had cast anchor in the
harbour of Piræus, which was full of men-of-war and other vessels
belonging to different nations. All had hoisted their flags, and the
Greek vessels were cannonading, for it was the 5th of May—King
George’s birthday. But I had no time to lose in looking at what was
going on in the harbour of Piræus, for in a few hours our boat would
leave for Messina, and I wanted to see Athens during that time. I am
almost ashamed to say that we did not stop a few days at Athens,
but there is only one boat in the week that leaves Athens for
Messina, and as we could not spare a week, we had to content
ourselves with a few hours. But shall I say the pleasure was not
great because it was short? Are not most of the greatest joys of life
counted by minutes and hours rather than by weeks and months?
It was a splendid morning, full of clouds and sunshine. The clouds
hung over the mountains, but over head smiled the blue Ionian sky.
What a pleasant drive it was from Piræus to the Acropolis. After the
roads of Turkey it was a great pleasure to drive at a quick pace over
a good one. The road was white and dusty, a true summer-road, of
which I am very fond. I should most probably have liked it better, if
the dust had not been blown into our faces, but I was that morning
not in a humour to find fault with anything. I think, in spite of much
that is attractive and interesting, I was inwardly glad to be out of
Turkey, and if ever I see it again it will not be from choice. The road,
after we had driven through some waste and barren land, led
through cornfields, where the corn seemed almost ripe; through
hayfields and vineyards, which were studded with olive and fruit
trees.
Before I left England, the wife of a soldier, who had accompanied
her husband to the Crimean war, told me that she had also been at
Athens, and that it was “not far from Greece.” I found it, however,
farther from Piræus than I expected. It is an hour’s sharp drive, and
although the hour passed pleasantly, it seemed long; perhaps
because my wish to see the Acropolis was great. We stopped,
however, first before the Temple of Theseus; I had seen it at some
distance from the window of our carriage, and had admired the
grand and noble structure. When I saw it near I found it was but
small, and admired the art that could make a comparatively small
and very simple building look so imposing.
A short walk brought us to the Acropolis, and when the keeper
unlocked the wooden gate, my heart beat at the thought that I was
in ancient Greece. With a strangely solemn feeling I ascended the
steps of the Propylæa, and then I found myself surrounded by the
glorious remains of those noble works of art which, for simple
grandeur and beauty, are unsurpassed by anything the genius of
man has since produced. Through those noble columns I beheld the
very same features of land and sky on which the sages, the orators,
the artists of Greece had gazed. I gathered a handful of flowers that
grew among the ruins. I picked up some tiny fragment of marble,
and looked at it with a feeling akin to that with which a devout
Roman Catholic contemplates a relic of his patron saint. At the same
moment my foot stumbled against a broken piece of a cannon-ball.
And then I remembered that the “barbarous Turk,” more than the
ravages of time, had changed these precious monuments of ancient
art into ruins; that the Turks had made a powder magazine of the
Parthenon, which exploded through a Venetian bomb, and destroyed
the Temple of Minerva. And I felt that the Greeks were not to blame
for hating them. I felt as if I should have liked to pull down with my
own hands the rude, ugly remains of the walls with which they have
disfigured the temples of the gods. I felt also very indignant against
the Venetians who had no small share in the destruction of those art
treasures. They should have known better than to commit such
sacrilege. And shall I not say that Lord Elgin, too, committed a great
wrong in carrying off those marbles that still adorned the Parthenon?
There, under the blue sky of Greece, was their home, and they
ought to have remained there. It is true enough that now they can
be seen by “the million” that visit the dim rooms of the British
Museum; but he has for ever robbed those that might have seen
them where they were first placed, of one of the greatest
enjoyments art can give to those that love the beautiful.
When we left the fine harbour of Piræus, the Captain pointed out
to us the Bay of Salamis, the Throne of Xerxes, the Tomb of
Themistocles, and other famous and interesting spots; but I listened
only with half attention, for my eyes tried still to distinguish the
Acropolis, and I cast many a “long, lingringlook behind;” steam and
wind, however, carried me quickly away, and soon I saw nothing but
the bare, cheerless coast of Greece.
Towards evening the movement of the ship became more violent;
the sea rolled in large foaming waves, and when towards nine
o’clock we turned Cape St. Angelo, we had some very heavy gusts of
wind, which produced such rolling of the boat, that I held to the
bench in order to keep my seat. It was a grand sight, but I have no
liking for that kind of grandeur, so I stumbled down stairs as well as
I could, in order to see no more of it.
On awaking next morning, I found, to my great satisfaction, that
the ship moved along with a motion hardly perceptible, the sky was
almost cloudless, and the air mild and balmy. That day passed
pleasantly. I wrote my letter to my children, read a Waverley Novel,
and watched the poor little swallows and turtledoves, that came with
weary wing to rest on the masts of our ship. One was so tired that a
boy belonging to the crew caught the little wanderer in his hand. We
gave it some food and water and a free passage to Sicily, where it
was set free.
I awoke early next morning, and peeping through my cabin
window, saw in the rays of the rising sun the coast of Calabria. “Ah
mio Lindoro presto vedremo l’Italia.” I sang, and awoke my husband.
We were soon on deck. The sea was calm, and the air as soft and
balmy as the day before. The coast of Calabria lay before us, and a
little towards the left towered Mount Etna, from whose snow-
covered crater arose a white column of smoke, as if Nature was
bringing there her morning sacrifice. As we neared the coast the sea
became enlivened with boats, whose white sails were reflected in
the mirror of the calm sea. We gradually came so close to the coast
of Calabria, that we could distinguish houses, trees, gardens, and
even human beings and cattle. Through my opera glass I
distinguished the very colours of the gaily dressed peasant women
that were going to mass, for it was Sunday, and about church time.
The first place at which I looked with special interest was Milito,
the little village where Garibaldi ran his ship ashore, when he came
to conquer Naples, and was pursued by Neapolitan men-of-war. The
Captain that pointed the place out to us, told us that there were still
some débris left of the vessel that brought the deliverer of Southern
Italy to the shores of Calabria. Then came Reggio, the Neapolitan
fortress which the brave Garibaldians took under the command of
our friend Colonel Chiassi, and a little further on lay Aspramonte.
What a story those three places tell! I looked with a feeling of deep
sadness at the mountains over which the flying Garibaldians had
carried their wounded General, and thought of Columbus brought
back to Spain in chains, of poor John Huss burned at the stake, of
Galileo languishing in the prisons of the Inquisition, and how the
world has ever cried “crucify him” against its benefactors.
The coast of Calabria looked cheerful and well cultivated; the
mountains have wild strange shapes, but at their feet are orange
groves, and mulberry plantations, with here and there, growing in
the midst of the bright green, the sombre foliage of the olive. I
observed many new comfortable looking houses, with large windows
and green shutters, which I hope speak of an improved state of the
country, and which contrast favourably with the old dwellings of the
Italian peasantry. The latter are generally very wretched looking
places, with small dismal looking holes instead of windows.
We stayed a day at Messina, and profited by it to look at the town,
the churches, etc. How everything is relative in this world. Had I
gone to Messina after visiting Florence and Naples, instead of
before, I should most likely have thought it a very insignificant
looking place. But after Constantinople and Smyrna, it looked a town
of palaces. The nice pavement, the fine large stone houses, with
their balconies before every window, on which dark girls in gay
Sunday dress stood among flowers. It looked quite grand, and very
pleasant. The churches are rich in precious marbles and gildings, but
built in a very degenerate style of architecture. The pictures with
which they are decorated generally represent tortured saints, and
are even less satisfactory than the buildings themselves. I wanted to
see a little of the country, and we therefore took a drive. I saw
however nothing of it, except a dusty road between high walls,
which seemed to enclose orchards, for the branches of orange, fig,
mulberry, and olive trees, were visible above the walls. I cannot tell
whether all the roads around Messina are like this one, or if our
coachman was to blame for his choice. We found it difficult to
understand the Sicilian dialect, and almost required an interpreter to
translate it into Italian.
We left Messina the following afternoon. The weather was still
calm and beautiful; the sky cloudless, and the sea shining in the
sunlight, as calm as a lake. A short time after we had left Messina,
we passed Scylla and Charybdis, the first only discernible by a very
slight movement in the water, the latter a rather prominent rock on
the opposite coast. It must have been very different in the time of
Homer, I should think, for even the boldest imagination could not
see in the present Scylla and Charybdis, anything like what Homer
describes it to have been. As for Schiller’s beautiful description of it,
in his ballad “The Diver,” it is purely imaginative, for Schiller never
visited Italy. The next day we passed Stromboli, an island formed by
a large volcano rising out of the sea. The mountain, a grand and
imposing cone, was in a somewhat active state, much more so than
Etna. I was sorry we did not see it by night, for the thick column of
smoke that rises out of it, then looks red and fiery. It was however
out of sight long before evening, but there were other lights burning
through the balmy night, and throwing rays of silver light across the
placid waters, Hesperus and “Cynthia’s shining orb.” It was past
midnight before we went down stairs, and we had slept but few
hours, when the bustle and noise that always follow the arrival of
the boat in port, awoke me. When I got on deck, the sun was rising
over Naples. I saw the Bay, and Vesuvius and Capri. All these
wonderful names were no longer empty sounds, but had become a
reality, and I rejoiced in that thought.
I have not spoken of any of my travelling companions since I left
Constantinople. The reason is, that they hardly deserved any special
notice. They were such people as any one is likely to meet. Several
English families, that had wintered abroad, and returned most of
them with coughs and sore throats. Some of the girls were very
pretty, perhaps all the more so because they looked so fragile, it
seemed one cold East wind would blow the pretty blossoms away.
Then there was a rich Jewess from Constantinople, with three
daughters, who were all “musical young ladies.” They were going to
some European watering-place, not for their health though, I should
think, for they looked as strong and hearty as one could wish. The
Messageries Impériales steamers are unfortunately provided with a
piano, which I consider a most inconsiderate arrangement on the
part of the Company; for I had to listen for several hours daily to the
performances of these young ladies, playing either singly or in
couples. The nuisance became almost intolerable, when they were
joined at Messina by a musical young gentleman, an officer from
Malta, who, between the fantasias and sonatas of the young ladies,
treated us to a succession of quadrilles and polkas. It broke into and
spoiled the calm enjoyment of one of the most beautiful moonlight-
nights on the Mediterranean, when nature seemed so hushed and
still, that I involuntarily spoke in whispers.
There were also two interesting honey-moon couples on board:
one of them always sitting in out-of-the-way corners, so that
perhaps I might have been altogether unaware of their presence, so
little were they in any body’s way, had they not turned up regularly
at meal times. The other couple never turned up at all, at least not
the lady. She was very poorly, and in fair or foul weather always
lying down in the Ladies’ Saloon; to the open door of which the
devoted young husband came ever so many times a day, offering
lemonade, coffee, and other refreshments to the sufferer, who
however seemed unable to relish any thing.
And I must not forget Miss L—, because of the singular adventure
that happened to her. She was of middle age and rather delicate
constitution, had spent the winter with some friends at Malta, and
was now on her way home. We had been neighbours at dinner, and
exchanged a few words. Early in the evening, after we had left
Messina, where she came on board, she came to me in great
agitation, and asked my advice under what were certainly trying
circumstances. The stewardess in showing her to her cabin, had said
that there would be but one other occupant, viz. a “jeune
demoiselle.” How surprised and horrified therefore was the poor lady
when, wishing to retire early, she had gone into her cabin, and saw
standing before the other berth a pair of man’s boots, and a man
lying dressed on it, who had his face covered with a silk
handkerchief. She rushed back and told the stewardess that there
was a man in her cabin. The stewardess however replied good
humouredly, and with a smiling face: “Non, Madame, ce n’est pas un
homme, mais une jeune demoiselle noire qui s’habille comme çà.”
She told her at the same time that she was sorry there was no
empty berth in any other cabin, as she seemed to dislike sleeping
with the “jeune demoiselle noire.” At this information, the slight
knowledge of the French language which Miss L— possessed,
seemed quite to forsake her, she found no words to reply, and came
in despair to me, as the only person with whom she had exchanged
a few words on board. “What am I to do?” so the poor thing
concluded her story, “I cannot sleep in the Saloon because it is full
of gentlemen, and to remain on deck would be sure to make me ill,
as I am very susceptible to colds.” I took her to my husband, as the
tribunal to which I appeal in difficult cases, and he at once reassured
her by his promise that he would take care she should not sleep in
the same room with the black person, who travelled under the name
of a “jeune demoiselle.” He went straight to the Captain, and what
the stewardess said she could not do, the Captain arranged. She
slept comfortably in the same room with some other ladies, who
neither wore male attire, nor “the shadowy livery of a warmer sun.”
Her gratitude to my husband was boundless, and she remained
my constant companion till we reached Naples, where we landed,
while she proceeded to Genoa and Marseilles. We saw the “jeune
demoiselle,” as we called the black person, a good deal on deck and
at meals. Miss L— always kept as far as possible away from her, and
I did not wonder at it. In looking at the African I felt more than ever,
that, although in theory the Americans may be to blame for their
manifest dislike to the Negroes; in practice I should find it very
difficult not to do as they do, and avoid any intercourse with them.
And I admired more than ever the heavenly kindness of Mrs.
Beecher Stowe’s little Eva, who broke her heart at the fate of this
race. I forget at this moment, if, according to Mr. Darwin’s theory, we
have a common origin with them, or are descended from them. In
the latter case I hope nobody will ever ask me the question Farinato
addresses to Dante in the Inferno: “Chi fur i maggior tuoi”—as I
should be rather ashamed to mention these ancestors.
Goethe quotes Pliny’s description of Naples, and what Goethe did I
surely may be allowed to do. Instead, therefore, of trying to describe
Naples myself, I will translate what he has quoted: “So happy, lovely,
blessed is that region, that one perceives Nature has rejoiced in her
work there. Such vital air, such continued salutary clemency of the
sky, such fruitful fields, such sunny hills, such innoxious woods, such
shady groves, such useful forests, such airy mountains, such far-
extending cornfields, such an abundance of vines and olive-trees,
such fine wool of the sheep, such fat necks of the oxen, so many
lakes, such an abundance of irrigating rivers and streams, so many
seas, so many harbours! The earth opens her bosom everywhere to
commerce, and, almost anxious to assist man, stretches her arms
into the sea.” After reading such a description, the well-known “Vedi
Napoli e poi mori,” does not seem very exaggerated; nor when
Goethe writes of his father: “It is said that he who has seen a ghost
can never more be joyful, so on the contrary one might have said of
him (his father) that he could never become quite unhappy, because
he thought himself always back again at Naples.” That the days I
spent there brought me enjoyment and delight, every one will easily
suppose. People always call Paris a “gay” place, and such no doubt it
is, still thousands and thousands lead a dreary and dismal life there,
which seems hardly possible in Naples. Nature supplies all the
necessaries of life in such abundance that even poverty ceases to
cause real suffering. The climate is so mild that the want of what we
should call indispensable clothing brings no discomfort; while a plate
of macaroni, a dried fish, or a slice of melon seems to be all the food
they require. They are exceedingly fond of music and dancing, and
the Neapolitan airs are lively and pretty, and pleased me more than
any I have heard in Italy. The performers who sing before the hotel,
the caffés and restaurants, and accompany their songs with the
guitar and the liveliest expression and gesticulations, look
delightfully merry and cunning. Many of them improvise in a ready,
pretty manner. Who can be sad and morose in a place like this,
where everybody looks smiling, good-natured and contented? To be
merry, joyful and happy lies in the air there, and is contagious like
an epidemic. And I do not think the expression of good-nature and
contentment one sees in almost every face, belies their feelings. The
Neapolitans appeared to be very kind-hearted, and to delight in
giving pleasure. We received, during our short stay at Naples,
several marks of good will from them, of which I remember one
especially with pleasure. We had stopped, on our way back from a
short excursion to Posilipo, at a pretty restaurant, where we took
some refreshments on an open platform overlooking the sea. While
sitting there, and looking at the Bay and all the beauty surrounding
it, a boat passed with a merry party in it, four of whom were
amateur musicians. They played on two guitars, a flute, and a
trombone. As soon as they saw us they stopped the boat right under
our platform and played a pretty Neapolitan air, with the simple
intention of giving us pleasure. When they had finished they greeted
us and left. We returned the kind salute, and listened to their
“renewed strain” till it became indistinct, and the accompanying
sounds of the trombone only reached us.
After the great variety of Eastern costume the dress of the
Neapolitans looked rather tame. The dress of the women is neat and
clean, their full black hair is well plaited and shines like satin; but
they wear nothing that can be called a costume, and I found even
crinoline introduced to a great extent. If it were not for the dress of
the different orders of monks and nuns, of boatmen and fishermen,
and here and there a contadina in her pretty dress, the crowd would
be not much more picturesque than an English one, from which
however it would be easily distinguished by the darker complexion of
the people, the animated features, and the lively gesticulations with
which they accompany all they say.
We were at Naples the week after the first Sunday in May, which
is one continual festival in honour of St. Gennaro, the great patron
saint of Naples. Thus I had an opportunity of witnessing the
celebrated miracle of liquefaction of the blood of the saint, which is
kept in two phials in the chapel “del Tesoro” adjoining the cathedral,
for the blood liquefies daily during the festival when high mass is
celebrated. The chapel is wonderfully magnificent; the three altars
with their ornaments, and the statues of more than forty saints,
being all of silver. The most magnificent of all is, of course, that of
Saint Gennaro standing on the high altar, whose mitre of gold is
covered with precious stones of great size, and who wears round his
neck enough ornaments to deck a whole crowd of queens and
duchesses. They are the gifts of different kings and queens of
Naples. Napoleon I., who stripped so many churches of their
treasures, made a present to this all-powerful saint, and Victor
Emanuel seems to have thought that in this respect he too must
follow the example of his predecessors, for the saint wears two
magnificent crosses of amethysts and diamonds, the gift of the Rè
Galantuomo. My husband did not approve of this, and even
expressed a wish that Garibaldi had melted down the gold and silver
saints, and invested the money so obtained in schools for the
people, and other public and charitable institutions.
But who can tell if even Garibaldi, the idol of the people of Naples,
and the saint they perhaps most adore after St. Gennaro, could have
done this. The priest to whom I expressed my astonishment, that
the treasures of this chapel had escaped the vicissitudes of so many
revolutions and wars, said it was evidently a miracle wrought by the
saint.
If the great St. Gennaro has as yet escaped peculation, the
common little saints that used to stand at every street corner of
Naples, have not fared so well of late. They were all of them
removed in one night, by order of General La Marmora, then
Governor of Naples. The people, especially the women, became
clamorous and noisy on the discovery next morning, but were told
that the Governor was so fond of the Saints, that he wished to take
better care of them. He had therefore removed the Saints from their
uncomfortable quarters in the street, to snugger ones in the
Churches and Convents, where they would be much better off. This
entirely satisfied the crowd.
The removal of the Saints, and that of the pigs of St. Antonio,
which Garibaldi effected, has much changed the appearance of the
streets of Naples. The pigs of the Convent of St. Antonio, that used
to run about in the principal streets of Naples, even in the fine
Strada Toledo, and which lived upon public charity, were a terrible
nuisance. The ignorant populace held these pigs of the holy fathers
in great veneration, and fed them well, and I have been assured on
good authority, that if a man had with his cart or carriage run over a
child in the streets, he might possibly have escaped unpunished, but
had he hurt a pig in that way, the infuriated mob would almost have
killed him.
The morning I went to hear High Mass in the Chapel del Tesoro, it
presented an animated and magnificent spectacle. The windows
were darkened by crimson blinds, to keep the strong sunlight out,
and the chapel was lighted up by numberless candles, the light of
which was reflected by the silver ornaments that deck the whole
chapel. The way up to the altar was lined with soldiers, I suppose to
prevent disturbances in the eager crowd that longed to kiss the
liquefied blood.
The people walked up in good order to the altar, but on the sides
down which they returned, there was a good deal of squeezing and
pushing. The priest that held the little glass case, containing the two
phials in his hand, and who showed them to the congregation, shook
the liquefied blood about, and thrust the case into the people’s faces
with so rudely irreverent a manner, that I, who am no believer in the
miracle, felt shocked; what impression it made upon the other
people I cannot tell. They looked however quite contented and
pleased. They were mostly priests and nuns, and persons of the
lower orders, but I observed also some who appeared to belong to
the upper classes.
While the crowd kissed the blood of the Saint the choir sang a
most beautiful mass, and the rich voices with which bountiful Nature
has endowed so many of her children under the blue sky of Naples,
filled the chapel with harmony, and made the chords of my heart
vibrate in unison. There was a bass voice among them that
reminded me of Lablache.
On the evening of the same day I had witnessed the miracle of
the liquefaction in the Chapel del Tesoro, the son of the famous
conjuror Bosco repeated the trick before the boxes crowded with
elegant ladies at the Theatre St. Carlo, but I did not go to see it.
Ever since I am out of my teens, I no longer care for conjuring
tricks; besides I had seen it done so well in the morning. I was
however told that the trick in the evening succeeded quite as well,
and was repeated several times before a smiling and applauding
audience. I visited most of the other principal churches of Naples.
The Church of St. Severo is full of fine modern statues. One
representing a man who is trying to free himself from the meshes of
a net in which he is entangled, and which is called “the snares of the
world,” is very clever. Another one called “Modesty” is graceful, but
as a representation of modesty, might have a somewhat thicker veil.
At the Museo Borbonico, now called “Reale,” I admired some of the
finest Greek marbles I have ever seen. The grand Torro Farnese, the
wonderful Hercules, of the same famous collection, a Flora, that
looks something between a Juno and a Venus, stately and graceful
at the same time, the most charming representation of virgin youth I
have ever seen. There is a whole room full of Venuses, of which one
is certainly very beautiful, although apparently too conscious of her
charms to please me very much.
“I must go up Mount Vesuvius before we leave Naples,” I said to
my husband, and he, not less desirous than myself to visit a volcano,
set out with me early the next morning, for the ascent of the
mountain.
I know it is considered a beautiful sight to see the sun rise from
the top of Vesuvius, but as it rises in the middle of May at a most
unreasonably early hour, we despaired of getting to the top before
the sun, so we let the god travel alone for several hours, and did not
leave our hotel in the Chiatamone till a little after six o’clock. An
hour’s quick drive brought us to Resina. Our way to the latter led us
through the village of St. Giovanni, where one sees nothing but
macaroni and pigs. Most of the houses are small macaroni
manufactories, and the fresh macaroni are on long sticks, hung out
into the street to dry. Most of the manufacturers keep a pig, which is
tied to some post in the street, not far from the door of the house,
or if a very tame, good little pig, runs about free.
After St. Giovanni, we passed through Portici, the home of
Masaniello and his poor sister Fenella. Here there are delightful
villas, with gardens sloping down to the bay, and close to it lies
Resina, where the ascent of the mountain on horseback begins.
There used to be a fine carriage road as far as St. Salvator, which is
about an hour’s ride up the mountain, but the lava streams of the
great eruption of 1859, have entirely destroyed it. We had not been
more than ten minutes on our horses, when we came to these
formidable traces of the last great eruption of the volcano. In broad
thick masses the lava had flowed down the sides of the mountain
into the blooming orchards and fruitful vineyards, to which the dark,
dead rivers of stone presented a striking contrast.
These lava streams have a strange and diverse appearance.
Sometimes the surface is roughly even and resembles immense
masses of curiously twisted burnt trunks, and branches of trees. At
other places it is more like a roughly ploughed field that by a sharp
frost has become still more broken up than by the plough. Between
the lava are large beds of ashes and cinders.
The ride to the foot of the cone, which lasted about an hour and a
half, presented no difficulty, for the road rises very gradually and is
broad, and lava presents a rough surface on which the horses’ feet
do not slip. The cone must be climbed on foot, and is a very tiring
piece of work even with the assistance of two guides, the one to pull
you up with the help of a band fastened round his waist, the other
pushing you up by placing one of his hands against your back. As
climbing does not easily tire me I wanted to walk up, to which my
husband however objected; so I had to sit down in a chair in which
the guides carried me up. One guide in front held the two poles
which were fastened to the chair in his hands, two men behind
carried each one on his shoulder, and thus kept the chair in a
horizontal position. It must be very hard work indeed to carry any
body for an hour up so steep an ascent; for my husband, although
he was assisted in the already described manner by two guides,
found it very tiring indeed. The men did it however cheerfully, and
with less appearance of fatigue than I had expected. When we had
reached the top, and my husband and the men had rested awhile,
we walked to the brink of the crater, and now I saw, with my own
eyes, the strange and grand spectacle to the description of which I
remember to have listened with almost incredulous wonder when a
little school girl, and which to see I had longed for ever since we had
passed Mount Etna and Stromboli.
The volcano was in a very fair state of activity. Thick volumes of
smoke issued from it, and about every two minutes there was a loud
report as of thunder or cannon, and then flames appeared, and
ashes and stones were ejected flying high up into the air, and falling
down with a rattling noise. It must not however be thought that we
stood close to the terrible opening out of which rose the flames and
smoke. Within the large crater from the brink of which we witnessed
the spectacle, rises, what looks a Vesuvius on a smaller scale, and
on the top of this, which is however below the level of the place
where we stood, is the real crater. It is very fascinating to watch the
eruptions, and we found it difficult to turn our backs upon it, and
look a little at the scene around us in the beautiful world below.
The top of Vesuvius looks terribly dreary; the dread abode of
horror and destruction. Nothing but the dark lava stones and ashes
all around. There is of course no trace of animal or vegetable life
visible anywhere. The sad monotony is however a little relieved by
the different colours of the lava and the stones; especially by the
bright yellow of the sulphur one sees in large quantities. This
hideous image of death and destruction rises abruptly out of Elysian
plains and vallies; its foot is washed by the azure sea dotted with
emerald islands, and above smiles a limpid sky.
The view is very extensive, because Vesuvius is a mountain of
considerable altitude; yet as it rises so abruptly out of the plain and
sea, the view has the distinctness of no great distance, which adds
much to its charm. It is lovely on all sides; but from the point that
overlooks Naples, the Bay and its lovely shores, the Mediterranean,
and the islands of Capri, Ischia and Procida, it is deservedly
considered one of the most lovely in the world.
In going up the volcano the guides had chosen a stony, rough
stream of lava, which affords a safe footing; in going down, on the
contrary, they chose a bed of fine cinders and ashes, and ran or slid
rapidly down. What it had taken us an hour to ascend, my husband
descended in six minutes, and I, chair and all, took only about
double that time. It is a very dusty affair, the black ashes whirl up
under the feet of the men, and envelope one completely. Never was
a tepid bath more refreshing than the one I enjoyed in the evening
after I had come home from my visit to Vesuvius.
The guides had pointed out to us the lava streams of the different
eruptions, and the immense stones and pieces of rock which were
ejected by the volcano in 1822. In looking at these formidable pieces
of rock, of which some were at a great distance from the crater, one
gets an idea of the power that is working within it, and the fate of
Herculaneum and Pompeii becomes intelligible. The latter place we
had visited the day before. All I felt there is expressed in those few
words: “Sic transit gloria mundi.” But never before had I realized so
fully what the instability of all earthly greatness means. In this city of
the dead I felt far, far removed from the present, and my mind for a
moment seemed to realize what the future really means. A time,
when the lovely city I had just left would have disappeared from the
face of the earth, and its old site be a matter of doubt and
uncertainty, when the language of Dante would survive perhaps in
his book only, when the very features of sea and mountain around
me might be changed; for had not eighteen hundred years ago, the
waves of the gulf washed the walls of Pompeii that now lies far
inland, and another Vesuvius burned than the one we ascended?
And I saw with my mind’s eye the proud city across the sea, which I
had left a few months before, as Macaulay, thinking of a time to
come, describes it, a heap of ruins; and a traveller in a strange
dress, speaking a language which is not yet formed, sitting on a
broken arch of London Bridge, meditating like me at that moment on
the truth of the words, “Sic transit gloria mundi.” We did not, as
Murray recommends, enter Pompeii by the Strada dei Sepolcri, but
through the Porta del Mare, and I liked it better, as the Strada de
Sepolcri forms the fittest finale of the town.
I have heard of people who have been disappointed in Pompeii,
others have said the same of the Acropolis. I cannot understand
such people. They must be more dead than the very stones there,
for they spoke to me, and what they said moved me deeply. When I
first entered the city of the dead, I felt strange and bewildered like
in a dream. Surely “reality is stranger than fiction.” What can be
more strange than that the sun should shine again into the streets,
and light up the painted walls and mosaic pavement of Pompeii. And
yet so it is. That very old Pompeii, that lay for nearly eighteen
centuries buried, is risen again. We walk through its streets, and
tread the very stones worn out by the footsteps of Roman citizens,
and by the wheels of their chariots.
We see their houses, their temples, their judgment halls, their
baths and theatres, their gardens and court-yards, in which however
the little fountain is silenced for ever. In walking into their houses we
seem to become strangely familiar with their former inhabitants; we
see everywhere traces of their being, of their virtues and vices, of
their greatness and their folly. I daresay by night the spirits of the
departed haunt the silent town; but it was by broad cheerful daylight
that I visited it, and therefore it seemed inhabited only by pretty
little lizards, which I saw flitting about on every wall, and between
the delicate ferns that grow in the silent streets of Pompeii.
Of our journey from Naples to Leghorn, there is not much to be
said, although it was very pleasant. We went with the Italian
steamer “Principe Umberto,” which was filled with passengers, most
of whom were going like ourselves to Florence, for the Dante
festival, which was to be celebrated there on the 14th, 15th, and
16th of May. Several of the passengers were deputies sent to
Florence from different towns in Calabria. The company was lively
and merry. The piano in the saloon sounded almost the whole day,
but being touched by skilful fingers it did not annoy me like the
performances of the young ladies from Constantinople, or the
quadrilles of the young English officer.
We arrived at Leghorn on the 13th of May, after a journey of
twenty-four hours, there we remained the night, not daring to
proceed to Florence, for we knew that all the hotels were over-
crowded, and that we should find it difficult to get a room if we
arrived late at night.
After a stroll through the town, which is a well built modern place,
we went to rest, in order to be better able to bear the fatigues, and
enjoy the pleasures of the days to come.
CHAPTER V.
THE DANTE FESTIVAL AT FLORENCE.

“Del bel paese la dove il si suona.”


Dante.

And now the great day had come, the 14th of May, 1865! I had to
rise very early, for we intended to leave by the first train, which
started from Leghorn at four o’clock in the morning. Although rather
averse to early rising in England, it cost me no effort here. The
thought of going to Florence roused me, besides the warm bright
twilight of an Italian May morning lighted up my bedroom, and the
street was already full of people, all in holiday dress, and taking the
road towards the station, in order to secure places in the train that
was to take them to Florence.
We were not the last in the crowd, and three hours after, arrived
at Florence, where Italy was going to celebrate on that day the sixth
centenary anniversary of the birth of Dante. Truly this solemn event
happened “in the fulness of time,” and every thing concurred to
make it as splendid and happy a festival as any nation has ever
celebrated. Now, for the first time, the grand idea of Dante, a free
and united Italy, has almost become a complete reality, and the
hearts of all his people rejoice that from the Alps to Mount Etna, one
law now reigns, and hopefully trust that the other great thought of
Dante, the deliverance of the Church from the burden of temporal
power, will ere long also become a reality. The disappointment and
irritation the Italians felt at the loss of Savoy and Nice, has almost
entirely passed, while what they have gained has still all the charm
of a new possession, and something of the passion and enthusiasm
of honeymoon-love in it. Is it therefore to be wondered at that the
people of Italy rejoiced on the 14th of May? that every countenance
wore a smile, and that their lively eyes sparkled with joy!
The festival happening in Spring-time was also a favourable
circumstance. Dante, near the entrance of Hell, felt comforted
because it was “la bella stagione,” was it therefore not natural that it
added much to the splendour and enjoyment of a fête in “blooming
Florence!” Had the anniversary happened in December or January,
where could the flowers have come from, and the glory of the
golden sunshine round Dante’s statue. A pelting rain might easily
have damped the enthusiasm of his countrymen, as it would most
certainly have spoiled the pretty bonnets of his fair compatriots, that
made so nice a show in seats round the Piazza Santa Croce.
Most favourable for the celebration of the anniversary of Dante’s
birth, was lastly, that it happened at Florence, the very town in all
the world best adapted for the celebration of such an event.
Fancy a national festival at Paris or London! The size of those
towns does not admit of a general decoration; but even if such a
miracle could be performed, nobody would ever see a tenth part of
it, as one would be nearly dead with fatigue getting half way from
the Marble Arch to St. Paul’s. Another serious drawback are the
immense multitudes that inhabit these monster towns, and create
unpleasant crowds, which, to all that have not nerves of iron, and
great physical strength, destroy all feeling of enjoyment. None of
these unfavourable conditions existed in Florence. It is but a little
place, though such a gem of a town, and can therefore be uniformly
decorated, changed into a gigantic palace, through whose halls and
corridors the inhabitants and visitors, that do not number by
millions, gaily move. And such a place Florence appeared on that
day. All the houses had red, green, or yellow silk hangings falling
down from their windows, and were besides richly decorated with
pictures, busts, flags, flowers, and evergreens. The noble
architecture of the town, the nice clean streets, which are neither
too narrow to look sombre, nor too broad not to be easily spanned
by garlands of flowers, all united to produce the happiest effect. On
all the principal places, statues of great Italians had been placed, or
trophies in remembrance of some great national event, which
happened on that particular spot. There was a great number of
them; for the Florentines boast, and not without some reason, that if
a stone were to mark every glorious memory of the town, there
would hardly be a stone in Florence that did not deserve special
distinction. I could not attempt to find out what all the statues and
trophies meant, but even if I had looked at them all, and
remembered every inscription, I could not enumerate them here,
else what is to be but a chapter would become a volume.
I must however mention a fine statue of Galileo, on the Piazza
Santa Maria Novella, with the following inscription:—
“A Galileo.
Finirà la tua gloria
quando il genere umano
cessi di vedere il sole ed abitare la terra.”[G]

[G]
Thy glory will end, when the human race
shall have ceased to see the sun, and to
inhabit the earth.

Near the Ponte alla Carraia, there was a statue to Goldoni, the
great writer of comedies, and on the Piazza del Duomo, those of the
famous architects Arnolfo and Brunelesco. On the houses where
celebrated men were born, lived, or died, tablets were placed
recording their names and deeds, ornamented with banners,
wreaths of flowers and laurels, and often with the bust or portrait of
the illustrious dead.
The Bruneleschi palace, where Michael Angelo lived and died, and
which still contains his books, furniture, etc., interested me much.
On a house in the Corso, I noticed the following inscription:—
O voi che per la via d’amor passate
volgete uno sguardo alle mure
ove naque nell’ aprile del 1266
Beatrice Portinari,
prima e purissima fiamma,
che accese il genio
del Divino Poeta
Dante Alighieri.[H]

[H]
You that walk in the path of love, cast a
look upon these walls, where in April 1266,
was born Beatrice Portinari, etc.

The house of Giovanni Battista Strozzi, named the Blind, the great
scholar and philosopher of the 17th century, was beautifully
decorated. I remarked also Frescobaldi’s, the friend of Dante, which
stands in the Via Maggio, and not far from it, on the Piazza Santa
Trinità, the house in which Robert Dudley, an English mathematician
of the 17th century lived, whose memory still survives in Florence.
In Sta. Maria Maggiore, I observed a tablet which marks the spot
where Brunetto Latini, Dante’s master, is buried. Under the name
was written the following line from the Divina Comedia, which is
deservedly considered a grander and more lasting monument than
any that could be erected in marble:
“M’insegnavate come l’uom s’eterna.“[I]

[I]
You taught me how a man becomes
immortal.

On the Piazza del Duomo, is the “Sasso di Dante,” a stone upon


which the great man often sat in meditations, as lofty and grand as
the glorious Dome on which he was silently gazing.
In a niche in the wall over that spot, was placed the bust of
Dante, surrounded by laurel wreaths and flowers. The Piazza dei
Signori, looked magnificent and most beautiful of all that part which
is formed by the Loggia dei Lanzi, under whose noble arches are
placed some of the finest works of art: the Theseus by Benvenuto
Cellini, the Rape of the Sabines by Giovanni di Bologna, and others.
This gem of architecture is at all times splendid, but now its walls
were covered with the most exquisite Gobelin tapestry, after designs
by Michael Angelo. They represented the history of Adam and Eve,
from their creation to their expulsion from Paradise.
The greatest care had however been bestowed on the decoration
of the Piazza Santa Croce, where the inauguration of the national
monument to Dante was to take place. This piazza is a large oblong
space, whose houses were covered with flowers and rich red silk
hangings, and the background was formed by the splendid marble
façade of the church of Santa Croce. The piazza had been boarded
and carpeted all over, and raised seats were erected for the
spectators who had obtained tickets. When these seats and the
windows round the piazza were all filled, principally with ladies, in
the most elegant spring toilets, the effect was the gayest
imaginable.
Behind the seats were placed thirty-eight paintings imitating bas-
relief, illustrating the life of Dante. The first represented him when,
nine years old, he first saw Beatrice, in the house of her father; the
last showed his burial in Ravenna. There were also the portraits of
about forty celebrated contemporaries, translators, or commentators
of Dante.
Round the piazza were placed rich banners of Florence and
Tuscany, the poles of which were festooned with wreaths of laurels
and flowers. On the pole of each banner was placed a tablet with
some verses from the great poem of Dante; many of which
anticipated the great political and religious events of the day, for the
accomplishment of which 550 years ago, Dante had longed with
passionate desire. I noted down a few, which I will transcribe here.
Soleva Roma, che’l buon mondo feo,
Duo Soli aver, che l’una e l’altra strada
Facean vedere, e del mondo e di Deo.
L’un l’altro ha spento, ed è giunta la spada
Col pastorale: e l’un coll ’altro insieme
Per viva forza mal convien che vada.[J]
Purgatorio, Canto 26.

[J]
Rome, that turned once the world to good
Was wont to boast two suns, whose several
beams
Cast light in either way; the world’s and God’s.
One since has quenched the other, and the
sword
Is grafted on the crook; and so conjoined
Each must perforce decline to worse, unawed
By fear of other.
Cary’s translation.
Di oggimai, che la chiesa di Roma
Per confondere in sè duo reggimenti
Cade nel fango, e sè brutta e la soma.[K]
Purg. Canto 26.

[K]
The Church of Rome,
Mixing two governments that ill assort,
Hath missed her footing, fallen into the
mire,
And there herself and burden much defiled.

Ahi, Costantin, di quanto mal fu matre


Non la tua conversion, ma quella dote,
Che da te prese il primo ricco patre![L]
Inferno, Canto 19.

[L]
Ah Constantine! to how much ill gave birth,
Not thy conversion, but that plentous dower,
Which the first wealthy Father gained from
thee.
Cary’s Dante.

Non fu nostra intenzion, ch’a destra mano,


De’nostri successor parte sedesse,
Parte dall’altra, del popal cristiano,
Nè che le chiavi, che mi fûr concesse,
Divenisser segnacolo in vessillo,
Che contra i battezzati combattesse.[M]
Paradiso, Canto 27.

[M]
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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like