100% found this document useful (14 votes)
57 views

Instant Ebooks Textbook Mastering JavaScript Single Page Application Development 1. Edition Klauzinski Download All Chapters

Mastering

Uploaded by

ekelinartens
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 (14 votes)
57 views

Instant Ebooks Textbook Mastering JavaScript Single Page Application Development 1. Edition Klauzinski Download All Chapters

Mastering

Uploaded by

ekelinartens
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/ 70

Get ebook downloads in full at ebookname.

com

Mastering JavaScript Single Page Application


Development 1. Edition Klauzinski

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

OR CLICK BUTTON

DOWNLOAD EBOOK

Explore and download more ebook 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]
Getting Organized with NPM,
1
Bower, and Grunt
JavaScript was the bane of the web development industry during the early days of the
browser-rendered Internet. It now powers hugely impactful libraries such as jQuery, and
JavaScript-rendered (as opposed to server-side-rendered) content is even indexed by many
search engines. What was once largely considered an annoying language used primarily to
generate pop-up windows and alert boxes, has now become arguably the most popular
programming language in the world.

Not only is JavaScript now more prevalent than ever in frontend architecture, but it has
become a server-side language as well, thanks to the Node.js runtime. We have also seen the
proliferation of document-oriented databases, such as MongoDB, which store and return
JSON data. With JavaScript present throughout the development stack, the door is now
open for JavaScript developers to become full-stack developers without the need to learn a
traditional server-side language. Given the right tools and know-how, any JavaScript
developer can create single page applications comprised entirely of the language they know
best, and they can do so using an architecture like MEAN (MongoDB, Express, AngularJS,
and Node.js).

Organization is key to the development of any complex Single Page Application (SPA). If
you don't get organized from the beginning, you are sure to introduce an inordinate
number of regressions to your app. The Node.js ecosystem will help you to do this with a
full suite of indispensable and open-source tools, three of which we will discuss here.

In this chapter, you will learn about:

Node Package Manager (NPM)


Bower frontend package manager
Grunt JavaScript task runner
Getting Organized with NPM, Bower, and Grunt

How these three tools can be used together to create an organized development
environment that is ideal for creating an SPA and is essential to the MEAN stack
architecture.

What is Node Package Manager?


Within any full-stack JavaScript environment, Node Package Manager will be your go-to
tool for setting up your development environment and for managing server-side libraries.
NPM can be used within both global and isolated environment contexts. We will first
explore the use of NPM globally.

Installing Node.js and NPM


NPM is a component of Node.js, so before you can use it you must first install Node.js. You
can find installers for both Mac and Windows at nodejs.org. Once you have Node.js
installed, using NPM is incredibly easy and is done from the Command Line Interface
(CLI). Start by ensuring you have the latest version of NPM installed, as it is updated more
often than Node.js itself:
$ npm install -g npm

When using NPM, the -g option will apply your changes to your global environment. In
this case, you want your version of NPM to apply globally. As stated previously, NPM can
be used to manage packages both globally and within isolated environments. In the
following, we want essential development tools to be applied globally so that you can use
them in multiple projects on the same system.

With Mac and some Unix-based systems, you may have to run the npm
command as the superuser (prefix the command with sudo) in order to
install packages globally, depending on how NPM was installed. If you
run into this issue and wish to remove the need to prefix npm with sudo,
see docs.npmjs.com/getting-started/fixing-npm-permissions.

[8]
Getting Organized with NPM, Bower, and Grunt

Configuring your package.json file


For any project you develop, you will keep a local package.json file to manage your
Node.js dependencies. This file should be stored at the root of your project directory and it
will only pertain to that isolated environment. This allows you to have multiple Node.js
projects with different dependency chains on the same system.

When beginning a new project, you can automate the creation of the package.json file
from the command line:
$ npm init

Running npm init will take you through a series of JSON property names to define
through command line prompts, including your app's name, version number,
description, and more. The name and version properties are required, and your Node.js
package will not install without them defined. Several of the properties will have a default
value given within parentheses in the prompt so that you may simply hit Enter to continue.
Other properties will simply allow you to hit Enter with a blank entry and will not be saved
to the package.json file, or will be saved with a blank value:
name: (my-app)
version: (1.0.0)
description:
entry point: (index.js)

The entry point prompt will be defined as the main property in package.json and is
not necessary unless you are developing a Node.js application. In our case, we can forgo
this field. The npm init command may in fact force you to save the main property, so you
will have to edit package.json afterward to remove it; however, that field will have no
effect on your web app.

You may also choose to create the package.json file manually using a text editor, if you
know the appropriate structure to employ. Whichever method you choose, your initial
version of the package.json file should look similar to the following example:
{
"name": "my-app",
"version": "1.0.0",
"author": "Philip Klauzinski",
"license": "MIT",
"description": "My JavaScript single page application."
}

[9]
Getting Organized with NPM, Bower, and Grunt

If you want your project to be private and want to ensure that it does not accidently get
published to the NPM registry, you may want to add the private property to your
package.json file, and set it to true. Additionally, you may remove some properties that
only apply to a registered package:
{
"name": "my-app",
"author": "Philip Klauzinski",
"description": "My JavaScript single page application.",
"private": true
}

Once you have your package.json file set up the way you like it, you can begin installing
Node.js packages locally for your app. This is where the importance of dependencies begins
to surface.

NPM dependencies
There are three types of dependencies that can be defined for any Node.js project in your
package.json file: dependencies, devDependencies, and peerDependencies. For the
purpose of building a web-based SPA, you will only need to use the devDependencies
declaration.

devDependencies are those which are required for developing your application, but not
required for its production environment or for simply running it. If other developers want
to contribute to your Node.js application, they will need to run npm install from the
command line to set up the proper development environment. For information on the other
types of dependencies, see docs.npmjs.com.

When adding devDependencies to your package.json file, the command line again
comes to the rescue. Let's use the installation of Browserify as an example:
$ npm install browserify --save-dev

This will install Browserify locally and save it along with its version range to the
devDependencies object in your package.json file. Once installed, your package.json
file should look similar to the following example:
{
"name": "my-app",
"version": "1.0.0",
"author": "Philip Klauzinski",
"license": "MIT",
"devDependencies": {

[ 10 ]
Getting Organized with NPM, Bower, and Grunt

"browserify": "^12.0.1"
}
}

The devDependencies object will store each package as a key-value pair in which the key
is the package name and the value is the version number or version range. Node.js uses semantic
versioning, where the three digits of the version number represent MAJOR.MINOR.PATCH.
For more information on semantic version formatting, see semver.org.

Updating your development dependencies


You will notice that the version number of the installed package is preceded by a caret (^)
symbol by default. This means that package updates will only allow patch and minor
updates for versions above 1.0.0. This is meant to prevent major version changes from
breaking your dependency chain when updating your packages to the latest versions.

To update your devDependencies and save the new version numbers, you can enter the
following from the command line:
$ npm update --save-dev

Alternatively, you can use the -D option as a shortcut for --save-dev:


$ npm update -D

To update all globally installed NPM packages to their latest versions, run npm update
with the -g option:
$ npm update -g

For more information on semantic versioning within NPM, see


docs.npmjs.com/misc/semver.

Now that you have NPM set up and you know how to install your development
dependencies, you can move on to installing Bower.

Bower
Bower is a package manager for frontend web assets and libraries. You will use it to
maintain your frontend stack and control version chains for libraries such as jQuery,
AngularJS, and any other components necessary to your app's web interface.

[ 11 ]
Getting Organized with NPM, Bower, and Grunt

Installing Bower
Bower is also a Node.js package, so you will install it using NPM, much like you did with
the Browserify example installation in the previous section, but this time you will be
installing the package globally. This will allow you to run bower from the command line
anywhere on your system without having to install it locally for each project:
$ npm install -g bower

You can alternatively install Bower locally as a development dependency so that you may
maintain different versions of it for different projects on the same system, but this is
generally not necessary:
$ npm install bower --save-dev

Next, check that Bower is properly installed by querying the version from the command
line:
$ bower -v

Bower also requires a Git version control system, or VCS, to be installed on your system in
order to work with packages. This is because Bower communicates directly with GitHub for
package management data. If you do not have Git installed on your system, you can find
instructions for Linux, Mac, and Windows at git-scm.com.

Configuring your bower.json file


The process of setting up your bower.json file is comparable to that of the package.json
file for NPM. It uses the same JSON format, has both dependencies and
devDependencies, and can also be automatically created:

$ bower init

Once you type bower init from the command line, you will be prompted to define several
properties with some defaults given within parentheses:
? name: my-app
? version: 0.0.0
? description: My app description.
? main file: index.html
? what types of modules does this package expose? (Press <space> to? what
types of modules does this package expose? globals
? keywords: my, app, keywords
? authors: Philip Klauzinski

[ 12 ]
Getting Organized with NPM, Bower, and Grunt

? license: MIT
? homepage: http://gui.ninja
? set currently installed components as dependencies? No
? add commonly ignored files to ignore list? Yes
? would you like to mark this package as private which prevents it from
being accidentally published to the registry? Yes

These questions may vary, depending on the version of Bower you install.

Most properties in the bower.json file are not necessary unless you are publishing your
project to the Bower registry, indicated in the final prompt. You will most likely want to
mark your package as private, unless you plan to register it and allow others to download it
as a Bower package.

Once you have created the bower.json file, you can open it in a text editor and change or
remove any properties you wish. It should look something like the following example:
{
"name": "my-app",
"version": "0.0.0",
"authors": [
"Philip Klauzinski"
],
"description": "My app description.",
"main": "index.html",
"moduleType": [
"globals"
],
"keywords": [
"my",
"app",
"keywords"
],
"license": "MIT",
"homepage": "http://gui.ninja",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"private": true
}

[ 13 ]
Getting Organized with NPM, Bower, and Grunt

If you wish to keep your project private, you can reduce your bower.json file to two
properties before continuing:
{
"name": "my-app",
"private": true
}

Once you have the initial version of your bower.json file set up the way you like it, you
can begin installing components for your app.

Bower components location and the .bowerrc file


Bower will install components into a directory named bower_components by default. This
directory will be located directly under the root of your project. If you wish to install your
Bower components under a different directory name, you must create a local system file
named .bowerrc and define the custom directory name there:
{
"directory": "path/to/my_components"
}

An object with only a single directory property name is all that is necessary to define a
custom location for your Bower components. There are many other properties that can be
configured within a .bowerrc file. For more information on configuring Bower, see
bower.io/docs/config/.

Bower dependencies
Bower also allows you to define both the dependencies and devDependencies objects
like NPM. The distinction with Bower, however, is that the dependencies object will
contain the components necessary for running your app, while the devDependencies
object is reserved for components that you might use for testing, transpiling, or anything
that does not need to be included in your frontend stack.

Bower packages are managed using the bower command from the CLI. This is a user
command, so it does not require super user (sudo) permissions. Let's begin by installing
jQuery as a frontend dependency for your app:
$ bower install jquery --save

[ 14 ]
Getting Organized with NPM, Bower, and Grunt

The --save option on the command line will save the package and version number to the
dependencies object in bower.json. Alternatively, you can use the -S option as a
shortcut for --save:
$ bower install jquery -S

Next, let's install the Mocha JavaScript testing framework as a development dependency:
$ bower install mocha --save-dev

In this case, we will use --save-dev on the command line to save the package to the
devDependencies object instead. Your bower.json file should now look similar to the
following example:
{
"name": "my-app",
"private": true,
"dependencies": {
"jquery": "~2.1.4"
},
"devDependencies": {
"mocha": "~2.3.4"
}
}

Alternatively, you can use the -D option as a shortcut for --save-dev:


$ bower install mocha -D

You will notice that the package version numbers are preceded by the tilde (~) symbol by
default, in contrast to the caret (^) symbol as is the case with NPM. The tilde serves as a
more stringent guard against package version updates. With a MAJOR.MINOR.PATCH
version number, running bower update will only update to the latest patch version. If a
version number is composed of only the major and minor versions, bower update will
update the package to the latest minor version.

Searching the Bower registry


All registered Bower components are indexed and searchable through the command line. If
you don't know the exact package name of a component you wish to install, you can
perform a search to retrieve a list of matching names.

[ 15 ]
Getting Organized with NPM, Bower, and Grunt

Most components will have a list of keywords in their bower.json file so that you can
more easily find the package without knowing the exact name. For example, you may want
to install PhantomJS for headless browser testing:
$ bower search phantomjs

The list returned will include any package with phantomjs in the package name or within
its keywords list:
phantom git://github.com/ariya/phantomjs.git
dt-phantomjs git://github.com/keesey/dt-phantomjs
qunit-phantomjs-runner git://github.com/jonkemp/...
parse-cookie-phantomjs git://github.com/sindresorhus/...
highcharts-phantomjs git://github.com/pesla/highcharts-
phantomjs.git
mocha-phantomjs git://github.com/metaskills/mocha-phantomjs.git
purescript-phantomjs git://github.com/cxfreeio/purescript-
phantomjs.git

You can see from the returned list that the correct package name for PhantomJS is in fact
phantom and not phantomjs. You can then proceed to install the package now that you
know the correct name:
$ bower install phantom --save-dev

Now you have Bower installed and know how to manage your frontend web components
and development tools, but how do you integrate them into your SPA? This is where Grunt
comes in.

Grunt
Grunt is a JavaScript task runner for Node.js, and if you haven't used it before, it is perhaps
the best tool you never knew you needed. You will find it useful for a myriad of tasks
including CSS and JavaScript linting and minification, JavaScript template pre-compilation,
LESS and SASS pre-processing, and so much more. There are indeed alternatives to Grunt,
but none with as large an ecosystem of plugins (at the time of writing).

There are two components to Grunt: the Grunt CLI, and the Grunt task runner itself. The
Grunt CLI allows you to run the Grunt task runner command from the command line
within a directory that has Grunt installed. This allows you to have a different version of
Grunt running for each project on your machine, making each app more maintainable. For
more information, see gruntjs.com.

[ 16 ]
Discovering Diverse Content Through
Random Scribd Documents
out of the bolt rope; the main topsail also split to pieces from the
fourth reef, leaving not a wreck behind, and we expected the ship
would upset under bare poles.
As second lieutenant, I was stationed on the forecastle, and
seeing a light right ahead I pointed it out to Tim Coghlan, our
master, who swore it was Dungeness light and that we were all lost;
at the same time asking me for the key of the case, as he was going to
step down for a lunch, being infernally hungry and thirsty. I asked
Captain Lee, who was on deck all night—for he was an officer that
never flinched, and where there was danger he was always to be seen
cool and intrepid—to take some refreshment. ‘Why,’ says he, ‘I don’t
know what to say about the eating part of the business, but I think we
shall get plenty to drink, and that presently.’
Had the gale continued at south, nothing could have saved us.
With a tremendous sea, and breakers at no great distance, there was
no chance of reaching the Downs as we could not get round
Dungeness; when in a dreadful squall of thunder, lightning, hail and
rain, the wind shifted to north or NNW, which is off the land, and
blew with the utmost violence. But towards daylight it got more
moderate and we stood for the Downs, where we anchored with part
of the convoy in a shattered condition, the remainder coming in soon
after. Two of them were lost on the French coast when the wind
shifted to the northward.
Captain Lee soon after left the ship, with the good wishes of
every officer and man on board. He was a brave, generous, and
meritorious officer, an excellent sailor and skilful pilot for the
British, as well as Irish Channels, and well deserving of the honours
he now enjoys. He was succeeded by Captain John Bazely, who was
one of the best officers in the navy for skill, activity, and high sense of
honour, well read, and possessing an excellent understanding, and
his death will long be lamented as a loss to the service and to society.
November 19th, another tremendous gale came on at SSW,
which lasted the whole of the day and most of the night. This was the
gale that Admiral Christian’s[120] fleet suffered so much in. We
expected every minute to part, and about the last quarter flood we
began to drive; but before we could let go our sheet anchor she
brought up. The Glebb, 74, the flagship of the Russian admiral
(Henikoff) lying abreast of us, parted and brought up with her last
anchor within half a mile of the Break. The Montagu, 74, under jury
masts, from the westward, anchored in our wake,[121] and run her
cable out to the clinch before she brought up. Had she parted, God
knows what would have become of us, as it was the height of the gale,
with thick weather, and nothing could have prevented her being on
board of us, as all her sails were blown from the yards. Had the gale
lasted much longer it would been of serious consequence to the ships
in the Downs.
Sailed with a convoy to the westward, which service we were
employed on, cruising occasionally in the Channel and Bay, for
several months. In May 1796, coming into Plymouth Sound from a
cruise, and blowing hard, we anchored astern of the Alfred, 74, who
had driven without our being aware of it, so that we found ourselves
in an awkward berth without room to moor. We then attempted to
get under way, but the gale increasing from the SW, we were unable
to weather Mount Batten and came to again. We soon after parted,
and let go another anchor and brought up between two rocks in a
perilous situation, with two anchors ahead; but fortunately it got
more moderate, and, observing there was an undertow, so that when
she pitched there appeared no strain upon the cables, we thought
there was no occasion to cut away our masts; and our opinion was
right, notwithstanding the wish of the knowing ones who came down
by hundreds and chalked in large letters on the rocks—‘Cut away
your masts.’ This was dictating with a vengeance by a set of vagabond
landsmen, fellows that could rob a house easier than knot a rope
yarn, and be damned to them. A lighter with an anchor and cable
came out soon after; and the wind shifting, we got under way and
anchored in a safe berth.
Sailed to the westward and cruised in the Bay, and on our return
to the Sound received orders to proceed to Spithead and fit for
foreign service, and about the latter end of August sailed with a small
convoy for Quebec. Nothing particular happened until we got on the
Banks of Newfoundland, when we fell in with a French squadron
under Admiral Richery. It was in the forenoon watch, blowing very
hard, the wind WNW with a heavy sea, under a close-reefed main
topsail and foresail, when we observed a ship of the line to windward
with her head to the SW, under the same sail. Made the private
signal, which was not answered. Most of our convoy had parted
company in the gale. Bore up and made sail. The enemy also bore up
and made all sail in chase until sunset, when he gave over chase and
hauled his wind to the northward. We hauled our wind also, and
stood to the southward. Separated from the remainder of the convoy
during the night, it blowing strong with thick weather. There was
great exultation at our outsailing the enemy, and some on board
were wishing to have another trial, and their wishes were not
disappointed; for in three days after, about six in the morning, two
line-of-battle ships were observed astern about two leagues off.
The private signal was made, but not answered. We were under
close-reefed topsails and foresail, steering WSW, the wind NW. The
enemy made sail and stood after us. We immediately let two reefs out
of the topsails, set topgallant sails and hauled the main tack on
board, with jib a third in[122] and spanker. It was neck or nothing, and
those who wished for another chase looked rather glum and had not
quite so good an opinion of our sailing on a wind as they had when
before it. For my part I expected we should upset, and it was with
uncommon alacrity in making and shortening sail between the
squalls that we escaped upsetting or being taken. The enemy knew
well what he was about, for he kept rather on our lee quarter with his
fore topmast studding sail boom run out, and the sail ready for
setting in case we had kept away. At one time his weather main
topsail sheet gave way and he was only ten minutes in setting the sail
again; his jib also split, which he unbent and had another set in
twenty minutes, which did him great credit. Luckily for us the sea
was nearly abeam; had we been on the other tack we must have been
taken, as we should then have bowed[123] the sea. I remember heaving
the log and she was going ten knots. But notwithstanding our good
sailing the enemy gained on us fast, and we should have been
captured for a certainty if the Frenchman had possessed more
patience.
Festina lente, not too fast;
For haste, the proverb says, makes waste.

And so it happened; for a little before six, when he was within


gunshot, the greedy fellow let another reef out of his topsails, and
just as he had them hoisted, away went his fore yard, jib-boom, fore
topmast and main topgallant mast. The other line-of-battle ship was
hull down astern. The chase lasted twelve hours, during which time
we ran near forty leagues. Shortened sail and wore ship, and as we
passed to windward, we counted fifteen ports of a side on his lower
deck.
Nothing further happened, except losing a poor fellow
overboard in the Gulf of St. Lawrence, until we got to Quebec. The
convoy also escaped and came in soon after; one of them was chased,
but by fixing a pole on a tub with a lantern on the top, and steering
another course in the night, escaped. We remained at Quebec until
the latter end of November, and then sailed with a couple of fur ships
for England under convoy. We left Quebec in the evening. I had the
first watch, and I never shall forget the cold as long as I live.
Nothing remarkable happened until we got to the southward of
Cape Clear, which bore north according to our dead reckoning, and if
I remember correctly on the 23rd of December 1796, about eight in
the evening we saw a squadron of men of war, one of them with a top
light, standing to the northward, the wind about west, and at no
great distance. We immediately hauled off to the southward, put out
all our lights and hailed the two vessels under our charge to do the
same. After standing to the southward some time, we altered our
course and saw no more of them. The wind soon after shifted to the
eastward and blew a heavy gale. Lost sight of our convoy and after
buffeting about for some days we were obliged, for want of fuel, to
put into Cork, where we found several men of war preparing to sail in
consequence of the French being off Bantry Bay. All the carriages
and horses that could be found were put in requisition to take the
troops to that quarter, and when we had completed our stores and
water we sailed with a squadron of frigates under Captain Jon.
Faulknor to the southward in quest of the enemy, but they had left
Bantry, where Lord Bridport was off with the grand fleet, who we
joined with our squadron. I believe this was the time that General
Grouchy with eight thousand men (before the arrival of our fleet)
anchored in the bay; but from fear, or some other cause, thought it
safer to set off than to land; and at Bantry, as well as at Waterloo,
shewed great want of judgment.[124]
We were attached to the grand fleet as a repeating frigate; and in
January 1797, we chased by signal and captured the French privateer
La Favorite, of eight guns and sixty men, out but a short time from
Brest and had taken nothing. After removing the chief part of the
prisoners, I was put on board as prize master with two midshipmen
and twelve men, with orders to stay by the fleet; but on examining
her defects I found her in a very bad condition, upon which I
separated from the fleet in the evening and stood for the Channel
(being then in the Bay). We had nearly been run down by a three-
decker—I believe the Prince George, commanded by the late Sir
Joseph Yorke—in the rear of the fleet, and the night being as black as
Erebus we had a narrow escape. Portsmouth being the place of
rendezvous, we stood up Channel with the wind at SW the day after
leaving the fleet, blowing a gale, under a close-reefed main topsail
and foresail.
We had not an observation for several days before we parted
from the grand fleet, and in running up Channel we got into Portland
Race. I have been in many noted places, but this infernal race was
worse than all, and I expected every moment we should founder. The
privateer being deep-waisted, I ordered her ports to be knocked out
so as to let the sea have a clear passage through; our hatches were
battened down, but we were in danger of being washed overboard.
The sea appeared like a pot boiling, and the spray beat over our
topsail yards. Hauled off to the southward, and fortunately got safe
out of one of the most damnable places I ever was in. The Frenchmen
were in the utmost terror and cursed the hour they ever left Brest. By
our account we were half way between the Start and Portland, which
was very fair considering everything. During the night it fell calm
and towards morning the wind freshened at SE with thick weather;
at daylight, stood in and sounded fifteen fathoms near St. Alban’s
Head, and, it clearing away, bore up and made sail for Plymouth.
When near the Start we hoisted the union jack over the French at the
gaff end; but the jack blowing away, and the halliards getting foul, we
could not for some time haul down the French colours, which
frightened a brig that was near, and a frigate coming from Torbay
under jury masts fired (I believe) at us but at too great a distance to
take effect. However, we got our colours to rights and I hailed the
brig, who seemed very much alarmed until I informed him we came
from the grand fleet, a prize to the Hind. In the evening we anchored
in Cawsand Bay, and next morning I waited on Sir Richard King, the
port admiral, who behaved in the kindest manner, and on my
explaining my reasons for leaving the fleet he said I did what was
very proper.
As no despatches had arrived, I was ordered by Sir Richard to
write an account of what happened in the fleet from the day we
joined Lord Bridport until I left with the prize, and also to give an
account of our proceedings from the time we fell in with Richery’s
squadron until our arrival at Cork. I was put into a room and desired
to take my seat at a table with a quire of foolscap placed before me;
and like a fool I looked, for it was a long time before I knew what to
write, or how to begin. At last I took courage, and filled three or four
sheets; bad grammar, no doubt. Sir Richard read the whole and said
it would do very well—many thanks to him. He laughed heartily
when I told him I got into Portland Race and what a panic the
prisoners were in.
I had sent a pilot off to take the brig into Hamoaze and walked
down with Sir Richard to Mutton Cove, as he wished to see her as she
passed. He told me he was once put prize master when a lieutenant,
on board of such another and had left the fleet as I had done and for
the same reason. This made me easy and quieted my fears. Captain
Bazely’s father was port admiral in the Downs, and I wrote to him
stating our arrival and received an answer thanking me for the
information respecting his son. We had not been long at Plymouth
before the Hind left the fleet and put into Portsmouth, and not
finding me there supposed we were lost, until Captain Bazely
received a letter from his father saying he had heard from me, and
that we were all well and safe at Plymouth, and in a few days I
received the following letter from Captain Bazely:

Hind, Portsmouth, February 1797.


‘Gardner, my good fellow, I am truly happy to find you are in the land of the
living, and that it was through necessity you put into Plymouth. We are ordered to
Sheerness to dock, where I shall be devilish glad to see you; so get on board some
vessel bound to the Downs with your party, and be sure to call on my father, who
will be very glad to see you and will send some craft to take you to the Nore. We are
all well.—Believe me to remain, with best wishes,
‘Yours most faithfully,
‘John Bazely, Junr.’
After clearing the prize and delivering her up to Mr. Hemmings,
the master attendant at Plymouth and agent for Lord Bridport (who I
have every reason to thank for his great civility while I remained in
Hamoaze, in the many invitations I had to dine at his house, where
he made a point to introduce me to the captains who visited there) I
was put on board the Medusa, 50, commanded by my old messmate
Jack Eaton, who was to take us as far as Portsmouth. On our arrival
at Spithead we were put on board the Weasel, commanded by
Captain Lewis, and sailed for the Nore, where we soon arrived and
joined our ship at Sheerness, and I was well received by the captain
and my messmates. Went into dock and when refitted proceeded to
Portsmouth, where we remained but a short time and sailed with a
convoy for Oporto. We had a very pleasant passage and took out
Captain A. Ball on his way to join his ship, who left us off Oporto. On
our return we recaptured a brig in the Bay of Biscay, and I was put on
board as prize master; but from ill health I went back to my ship and
the first lieutenant took charge of the prize in my room.
On our arrival at Spithead, the latter end of April 1797, we found
the fleet in a high state of mutiny. We had orders to fit for foreign
service, and I had directions to go with a party of seamen and
marines to the dockyard for new cables and stores. The mutiny,
which in some measure had been suppressed, broke out afresh on
board the London, 98, Vice-Admiral Colpoys, and some of the
mutineers were killed; but the officers were overpowered and the
admiral’s flag struck by the scoundrels, and the bloody flag of
defiance hoisted in its room. I went with my party to the yard in the
morning and began to get off the stores, when a marine said he
would not assist in rousing the cable into the lighter and advised the
others to knock off; upon which I told him if he did not immediately
take hold of the cable with the rest I would cut him down (which was
my intention). This had the effect and he went to work with the
others. When I got on board our men were in a state of mutiny, and
every ship at Spithead and St. Helen’s the same. I had the first watch
that night, and the master relieved me at twelve, and everything
seemed quiet; but about three bells in the morning watch I was sent
for by the captain, and on my coming on deck I found the ship’s
company assembled there and the captain, in the most impressive
manner, requesting them to return to their duty, but all to no
purpose. Had we been the only ship, we should soon have driven the
scoundrels to the devil; but as we were situated, surrounded by line-
of-battle ships acting in the same disgraceful manner, it would have
been of little use to resist. About six a paper was handed up to the
captain with the following order in writing:—
‘It is the unanimous opinion of the ship’s company that Captain
Bazely, Lieutenants Hickey and Gardner, Mr. White, the purser, and
Messrs. Kinneer and Allen, midshipmen, are to quit the ship by 6, or
violent measures will be taken to enforce the order.’
Soon after 6 the barge was manned and armed; every vagabond
had a cutlass, and our trunks were handed in, with orders from the
delegates not to carry them anywhere for us. I had a brace of pistols
with a double charge which I put in my great-coat pockets in case I
should want their assistance. It was blowing a gale of wind at NE
when we left the ship, and near ten o’clock before we landed on Point
beach; our things were handed out, and I desired the bowman and
one or two more, who I knew to be great scoundrels, to take them to
Turner’s (living on the beach, and only a step from the boat) shewing
them at the same time my pistols and saying, ‘You understand me.’
They then most reluctantly took our things to the place I directed.
This was all I wanted, as I heard some of the ringleaders say as we
were quitting the ship ‘that if any of the boat’s crew assisted in taking
our things to any place after landing they should be severely ducked
on their return’; and they were as good as their word; for those
fellows got a fine ducking the moment they got on board, the others
having reported them.
We left the Hind in May 1797, but before I close my account I
must relate a few anecdotes as they come to my recollection. I shall
begin with the surgeon, who was a very worthy fellow and much
respected, but was strange, so that we thought him half cracked, and
he had the name of Benjamin Bullock the Madman (a character in
some work that I forget). I was one morning walking the deck with
him when the postman came on board and presented a letter
directed to ‘Robert Anderson, Esq., or Benjamin Bullock, Esq.,
Surgeon of H.M. ship Hind. With speed.’ The letter ran thus: ‘Take
care when you are going on shore, and do not on any account pass
the Devil’s Point where Bullocks are put to death daily for the use of
the fleet. So no more at present from yours to command, J. Talgol,
Slaughter House, Devil’s Point.’
He accused me of writing the letter, but he was mistaken, and
from that day to this I know nothing of the author. He was greatly
enraged and vowed vengeance against me and my friend Harley the
purser, who was the person that gave him the name of Ben Bullock.
It happened some time after that Harley and myself were going on
shore and Anderson said he would take a passage with us. When
near the Devil’s Point, which we had to pass, I gave orders to the
boat’s crew to pull with all their might, ‘Give way, my lads, give way
until we pass this place.’ Anderson looked at me and said, ‘What the
hell are you afraid of now? You are always croaking about some
damned thing or other.’ ‘My good fellow,’ says I, ‘it is on your
account that I am so anxious. Don’t you remember the friendly letter
you had warning you to beware of the Devil’s Point? It is on this
account that I want to pass it in such a hurry, as you may be taken
out and cut up for fresh beef.’ And what made things worse, on our
landing the first object that drew our attention was a large board
over a warehouse, with ‘Bullock and Anderson’ on it in gilt letters of
immense size, to his astonishment and vexation.
At another time, when we had a large party on board I was
sitting at the bottom of the table and Anderson at the head as caterer.
I happened to be in conversation with Harley, who in the heat of
argument was energetically moving his hand up and down; which
Anderson observed, and leaving the head of the table with a knife in
each hand, he placed himself between me and Harley, and holding a
knife against our breasts says he: ‘That’s for thee, and that’s for thou;
I know well what you meant by moving your hand up and down like a
cleaver cutting up bullocks for the fleet, and be damned to you both.
Now do it again if you dare.’ After some difficulty we persuaded him
to go to the head of the table again; but those who were strangers to
his whims looked on him with an evil eye.
Our master (Coghlan) was a very droll fellow and fond of
carrying sail in a boat. Being sent from the Sound to the dockyard on
duty, it came on to blow a heavy gale of wind, and we struck yards
and topmasts. In the first watch about six bells I was walking the
deck with Captain Lee, who observed how glad he was our boat was
safe, as he had no doubt Mr. Coghlan had gone on board the flagship
in the harbour. He had not long made the observation, when I
thought (it being moonlight) I saw something in the direction of
Drake’s Island and pointed it out to Captain Lee, who said it could
not be a boat, as nobody would be mad enough to risk his life on such
a night. By this time the object drew near, when to our astonishment
we were hailed by Coghlan to throw a rope, and in a moment he flew
alongside. We got the yard and stay tackles over instantly, got the
men in, and ran the boat up in safety although a heavy sea was
running. When Coghlan came upon deck, the captain asked if he was
not ashamed of himself in risking the lives of the people in the
wanton manner he had done. Tim with the greatest simplicity said,
‘Sir, if you had seen her (meaning the boat) fly from the top of one
sea to another without stopping between, you would really have
admired her. She darted through the breakers when crossing the
Bridge (a dangerous reef of rocks between Drake’s Island and Mount
Edgcumbe) like a race horse. I never was in such a boat in my life.’
Captain Lee, vexed as he was, could not help smiling, at the same
time telling Tim if he did so again strange things would take place.
Coghlan’s name was John, but someone had written to Steel saying
his name was Timothy and it was put so on the list. Coghlan on this
wrote to say it was not his name and requested Steel to alter it; but
the same wag who had written before did so again, and when the list
was printed his name stood as John Timothy Coghlan, and remained
so, and we always called him Tim.[125] He has gone to his long home
and has left behind the character of an honest and worthy fellow. He
left the Hind to be master of the Trent, 36, going to the West Indies. I
dined with him a short time before he sailed, and he was pointing out
the different members of the mess, saying that none of them could
live in such a climate. Poor fellow, he little thought while making that
remark that they all returned and he the only one that sunk the
victim of all-conquering death.
At the time we had nearly got on shore and lost an anchor near
the Mewstone, when working out with the convoy, I was sent the
next morning to acquaint Commissioner Fanshawe[126] of the
circumstance, and to request he would order a lighter with a new
cable and to weigh the anchor we had lost. I recollect he was dressed
in an old blue coat with a red handkerchief about his neck, and in a
very crabbed humour. After staring at me for some time he roared
out, ‘I shall do no such thing. What brought you there? Go and tell
your captain if he gets into a hole he must get out of it again. I shall
give him no assistance and you may be off and tell him so.’ I told him
that we were out of the hole and that I only delivered my orders as I
was directed. At the same time I would thank him to write down the
words he had just made use of, as verbal messages were uncertain.
‘Be off, sir,’ says he, ‘and if your memory is good enough to recollect
what your captain said you cannot forget what I have stated; so no
more palaver’; and grinning at me with a horrid set of teeth, he
concluded by saying, ‘I have other things to think of than bothering
my brains about people who get into a lubberly situation and don’t
know how to get out.’ I looked at him without making any reply,
when, turning on his heel, he said, ‘Aye, you may look’;
Nor more he deigned to say,
But stern as Ajax’ spectre, strode away.

As I am not fond of making mischief, I thought it best to say


nothing to Captain Lee but merely state he refused to send the
lighter. This put the captain in a terrible rage, but the lighter being
sent off the next morning, the matter ended. Commissioner
Fanshawe was one of the first seamen in the navy, and also one of the
bravest officers that ever did honour to the service, a rigid
disciplinarian, and to sum up all, a tight hand of the watch, as the
saying is.
Coming from the westward to the Downs and when round the
Foreland, the captain ordered the colours to be hoisted, when up
went a swaggering French ensign and jack, which at first was not
taken notice of, but was soon observed by the captain, who ran
forward calling out to me, ‘Look at the French jack, sir; haul it down
directly.’ ‘Sir, said I, ‘the French ensign is at the mizen peak.’ This he
had not seen, and I thought he would have gone jumping mad.
However, they were hauled down; but as if the devil would have it,
instead of our own, up went Dutch colours. Nobody could keep their
countenance, and a general laugh went through the ship and also in
the men of war lying in the Downs who had observed the transaction.
While at Carrickfergus we were on very friendly terms with the
officers of the Irish militia and dined often at the different messes. I
remember on a rejoicing day calling with some more on the officers
of the Cavan militia. On going upstairs to their messroom, we found
several seated round the fire with a half barrel of gunpowder busily
employed making fireworks for the evening amusement. Our visit
was not of long duration, and I can truly say for myself that I only
made one step downstairs and was off like a shot—
Nor cast one longing, lingering look behind.

When in Hamoaze our boatswain was tried by a court martial for


repeated drunkenness and dismissed the service. At the trial the
captain of the Tremendous, 74, was unable to attend from
indisposition, and the surgeon being sent for to attend the court and
give in his report, he happened to make some remarks that the court
considered disrespectful; upon which he was given in charge of
Lieutenant Richards, first of the Cambridge, 84, on board of which
ship the trial took place, until the court should determine. He was
not long kept in suspense, for on the court opening he was sentenced
to three months’ imprisonment in the Marshalsea for contempt of
court,[127] and sent off that day. People should be careful.
On the passage to Quebec, after parting from our convoy, about
eight in the evening, with little wind and going two knots, and
nothing in sight, a voice was heard astern hailing, ‘On board the
Hind, ahoy!’ I must confess I was a little staggered, and some curious
remarks were made by the seamen. One fellow said, ‘I’ll be damned if
we were off the Cape but I should think it was the Flying Dutchman.’
‘As to that,’ says another, ‘he has got a roving commission and may
cruise where he likes.’ ‘Bad luck to me,’ says a marine, ‘if it’s not a
mermaid.’ ‘And to sum up,’ says old Macarthy, the quartermaster, ‘it
may be the poor fellow that fell overboard the other day.’ However,
the voice hailed again, saying, ‘Bear a hand and send the boat, for I’m
damned if I can keep up much longer.’ The jolly boat was
immediately lowered down from the stern and sent in the direction
of the voice; and will it be believed that the fellows were afraid to
take into the boat one of the main topmen (who had fallen overboard
out of the main chains, being half asleep) until he had told his name
and answered several ridiculous questions?
At the time we took the privateer, it was given out by our lying
newspapers that the French were starving. On the contrary the
French officers told me that everything was abundant in France, and
—if I may judge from what was on board—their account was correct;
for she had barrels of meat of every description—alamode beef, ham,
fowls, and tongues, casks filled with eggs, coffee, tea, and sugar, all
kinds of cordial, with plenty of brandy and different wines; so that
instead of starvation, there appeared the luxury of Lucullus, when
supping in the Apollo.[128] The French officers belonged to some of
the line-of-battle ships at Brest, but had leave from the French
Government to go on board privateers for a certain time and cruise
after our merchantmen. When we arrived at Plymouth they
requested me to state this to the proper authorities in the hope of
getting their parole. This I accordingly did, but without success, as
they were given to understand that being taken in a privateer they
could not be considered as officers entitled to parole.[129]
I found them very intelligent gentlemen; one of them spoke
English remarkably well and gave a very interesting account of the
revolution and of the leading characters then in power without any
partiality. The opinion, he said, in France was that the nobles and the
clergy were the instigators of anarchy and confusion, and the people
did not know how to put a stop to it. I must here mention that one of
our men who I had placed as a sentry, fell asleep at his post, which
was observed by a French officer who, to his honour, informed me of
the circumstance. I need not say how I thanked him. When they were
sent to Mill Prison I went with them and did everything in my power
in recommending them to the officers belonging to the prison, who
promised to make them as comfortable as they possibly could. I had
but little money, which I divided among them. We shook hands at
parting and they gave me their address, saying how happy they
should be to see me in France when the war was over. One of those
gentlemen had been a prisoner before in England and had his
quarters at Petersfield.
Richard Lee, Esq., Captain.
An admiral of the blue, K.C.B., Knight of the Tower and Sword.
An excellent officer and seaman. He commanded the
Courageux, 74, when Sir Richard Strahan captured Dumanoir’s
squadron. [Died 1837.—Marshall, ii. 568.]
John Bazely, Esq., Captain.
Dead [1827]. A vice-admiral of the blue. He was one of the best
officers in the navy, and much lamented by numerous friends
and particularly by his old shipmates.
Frederick Hickey, 1st Lieutenant.
A post captain and magistrate at Swansea; an excellent officer.
[Died 1839.—Marshall, vii. 227.]
Jas. A. Gardner, 2nd Lieutenant.
A commander.
John Coghlan, Master.
Dead. A most worthy fellow.
[George] Paton, Master.
Dead. A quiet, good sailor.
Christopher Noble, Lieutenant of marines.
Dead from his wounds. A major; as brave and generous a
fellow as ever lived.
Geo. White, Purser.
Dead. He had many good qualities, and many bad ones.
Robert Anderson, Surgeon.
Dead. A very strange and worthy fellow.
Robert Dunham, Acting Lieutenant.
Dead. A lieutenant. He was made lieutenant in 1781, but broke
and was reinstated in 1795; a very clever fellow, but as
obstinate as the devil.
[James] Moore, Gunner.
Dead. A very good sailor.
[Archibald] Freeburn, Gunner.
Uncertain.
Flemming, Boatswain.
Uncertain. Broke by court martial; a very good seaman but
drank hard.
[Christopher] Humphries, Boatswain.
Dead. A very good seaman and much respected.
[Robert] Biggery [or Bagrie], Carpenter.
Superannuated; a very worthy fellow.
[George] Porter, Mate.
A commander; a smart officer.
[John] Nazer, Mate.
Dead. A lieutenant; a very good and very ugly fellow.
[Thomas] Allen, Midshipman.
Drowned. A fine spirited young man.
[Benjamin] Badcock, Midshipman.
Drowned. A fine spirited young man.
[James Jervis] Kinneer, Midshipman.
Drowned in the Lutine, 36; a lieutenant.
Francis Geary Gardner Lee, Midshipman.
Sir F. G. G. Lee; a major in the royal marines and lieutenant-
colonel in the Spanish army.
Chubb, Clerk.
Drowned in the cutter with poor Allen.
[Jonas] Toby, Clerk.
Dead. A purser. [Purser of the Euryalus at Trafalgar; author of
the plan of the battle which was sent home to Lord Barham,
and published as a separate sheet and in the Naval Chronicle,
vol. xiv.]
BLONDE, 32

I was appointed first lieutenant of the Blonde, 32, Captain Daniel


Dobree, and commissioned her at Chatham early in March 1798, and
soon after got a draft of twenty-seven hands and a midshipman from
the Standard, 64, which was all I had to fit her out with, and of that
number, only five knew how to turn a dead-eye in. However, we
contrived to get her hold stowed, sails bent, and topgallant yards
across, before we had any addition of men or officers. At last our
complement was completed by a draft from the Dordrecht,[130] 64,
and went to Black Stakes, where we took in our powder and
proceeded to the Downs. We had a crack ship’s company with our
last draft, and in getting topgallant yards up the morning after we
arrived, we crossed ours, sent them down again, and then swayed
away and had them ready for crossing before the flagship and the
rest of the men of war at anchor. Vice-Admiral Peyton[131] was the
port admiral, and had his flag on board the Overyssel,[132] 64,
commanded by my late worthy friend Captain John Bazely. I
expected we should have got a reprimand for being too hasty in our
movements, especially when I saw a boat coming from the flagship;
however, instead of a rub down, it proved to be a visit from Captain
Bazely, who paid us many compliments on the good order the ship
appeared to be in. He told me there was a vacancy on board the
flagship for a lieutenant and that he would apply for me if I wished it,
at the same time stating that he was on bad terms with the admiral,
who was at all times a harsh and disagreeable officer, and in the
event of his getting a frigate (which he was in expectation of) he had
no doubt would prevent me (to annoy him) leaving the flagship, and
advised me to remain in the Blonde until he had an opportunity of
serving me.
Having received orders, we proceeded to Spithead and took
command of a small squadron of gun-boats and cutters to guard the
Needles passage, and anchored off Jack in the Basket, near
Lymington, which service we performed very agreeably for several
weeks. The rebellion in Ireland taking place, we were ordered with
several men of war and transports to proceed to Weymouth and
embark troops for that country. The king, being at Weymouth at the
time, with the royal family, it was expected he would review the
squadron; but the news from Ireland being very serious, the troops
were embarked in a hurry, and we got under way in company with
the men of war and transports for our destination.
I must here mention that the commodore of the squadron
(Captain Hardy,[133] commanding a 64) came on board with several
other captains, and after going round the ship and mustering us at
quarters, he addressed me, saying, ‘Sir, I feel great satisfaction in
stating that the Blonde is in the best order of any ship in the
squadron and the fittest to receive his Majesty, should he go afloat;
and for the short time your ship has been in commission she does
great honour to her captain and officers.’ This he said before the rest
of the captains, and among the number was my old captain (Towry)
formerly of the Berwick. In fitting out the ship at Chatham, I did
everything I could to keep on good terms with the officers of the yard
by asking them down to our mess and paying them every little
attention in my power; and by that means I had an opportunity of
getting many things done to beautify the ship.[134] I had the head
painted in colours, the quarters friezed, a famous stand made for the
arms on the quarter deck, and trophies painted on our scuttle butts,
with half circles and circles for our pistols and cutlasses, which made
the old Blonde cut a dashing appearance.
Just as we were getting under way, Captain Hardy sent me four
or five buckets of paint, with his compliments, saying I should stand
in need of it after getting rid of the soldiers, which was really the
case, as on board they were the most helpless and dirty devils I ever
beheld—except the Russians. It was impossible to get them up from
between decks without burning green wood in the stoves, which the
devil himself could not stand, the smoke was so intolerable.[135]
After a quick passage we landed the troops at Waterford, where
we remained a short time and then returned to our station, to guard
the Needles passage for a few weeks. The Europa, 50, being sent to
relieve us, got aground near Gurnet Point, and after lying there some
time was got off and returned to Portsmouth to refit. More troops
being ordered to Ireland, we were put under the orders of Captain
Geo. Burdon and sailed with a small squadron consisting of the
following men of war:—

Alkmaar[136] 54 Capt. Geo. Burdon, commodore


Tromp[137] 54 Capt. Worsley
Blonde 32 Capt. Dobree
Weymouth store-ship

On the passage we had near got on the Seven Stones. I had the
morning watch, and soon after I relieved the deck I observed
breakers upon the lee bow and beam and at no great distance; the
wind about NNW, and our heads to the westward, blowing fresh with
a chop of a sea. The Alkmaar was ahead, on the weather bow, and the
Tromp to windward, the Weymouth astern of all. We were under
double reefed topsail and foresail and no time to be lost; immediately
set topgallant sails, jib and spanker; hauled on board the main tack,
kept her rap full, and when she had fresh way, put the helm down
and she stayed like a top. We made the signal for standing into
danger, and when the Alkmaar put her helm down she missed stays,
and when they got her head round her stern was close to the
breakers. The Tromp, by being to windward and carrying a press of
sail weathered the shoals and parted company. In consequence of
foul winds we put into Scilly for a few days, and then sailed for
Dublin, where we landed the troops.
We were employed upon this service from Dublin to Cork and
then to Guernsey, and up and down Channel with convoy, until
August 1799, when we received orders to proceed to the Baltic to
convey the Russian troops to Holland. Sailed from Spithead, and
having taken in pilots proceeded to Elsinore and then to Reval, with
some transports. Found lying in the roads the Russian fleet
consisting of 15 sail of the line besides frigates, etc., under Admiral
Henikoff, and several British men of war and transports. Having
embarked some thousands of the Russian guards we left Reval for
the Texel, in company with British and Russian men of war and
several transports. We had on board a Russian captain, two subs., a
surgeon, and 296 privates, all hoffs, choffs, and koffs. The captain’s
name was Peter Glebhoff, who never pulled his boots off the whole
time he was on board. The men were the most filthy I ever met with.
They used to scrape the tallow out of the bottoms of the lanterns and
make it up into balls, which they would swallow and wash down with
a drink of train oil. They had bread made on purpose, of the coarsest
flour mixed with vinegar, and their cookery it is impossible to
describe; so that the Spartan black broth must have been a luxury
(however unpalatable) to their abominable messes. I have positively
seen them pick the vermin off one another’s jackets, which they
would eat without ceremony.
On our arrival at the Texel the whole were immediately landed,
and were soon after in action, and the most of those we had on board
put hors de combat by the next day. Poor Peter Glebhoff, who had
been sharpening his spear at the grinding stone a few days before the
landing, and vowing to sacrifice every Frenchman he met with, was
one of the first that fell. He had been in most of the battles under
Suvorof against the Turks and Poles, and had left a wife and family at
Riga to lament his fate. He was much liked while on board of us and
we all felt heartily sorry for him. I was several times on shore and
saw the numerous wagons of wounded soldiers from the scene of
action which by no means corresponded with the accounts given in
our Gazettes.... I had two cousins, captains in the 17th regiment of
foot—one of them (Knight) was killed just as I was going to see him.
A short time before we left the Texel the Blanche, 32, Captain
Ayscough, got on shore on the Haaks—a dangerous shoal near the
Texel, and some of the boats that were sent to her assistance
unfortunately upset, and several officers and seamen perished, owing
to the surf which ran very high on and near the shoal. The Blanche
got off, and returned to the New Deep, and sunk just as she entered,
but none of her crew were lost.[138] At this time things looked rather
queer, and it was found out after hard fighting that it was not so easy
to beat the French out of Holland as at first expected; and we were
ordered to take a cargo of runaway Dutchmen on board, with their
wives and families—about 400 altogether. A short time before we
sailed we saw the Lutine, 36, Captain Launcelot Skynner, at the back
of the Haaks, and, if I am correct, the evening she was lost[139] and
only one saved, who died soon after.
We left the Texel in November 1799, and in standing over to our
own coast had nearly struck by the blunder of our pilots on the
Gabbard. After escaping from this first blunder we anchored near the
Shipwash, another shoal by far more dangerous than the former. It
was in the evening that we took up our quarters in this precious
situation, intending to get under way with the morning tide. I must
here mention that we had two pilots; one of them had been a branch
pilot for more than twenty years. I had the morning watch, and on
relieving the deck I observed to this branch pilot that the weather
had a very suspicious appearance. The wind at this time was
favourable for getting to sea, and we could lay five points to
windward of the tail of the shoal. I strongly urged the pilot to get
under way, pointing out the danger of our situation should the wind
get dead on the shoal, but all to no purpose. He said there was no
fear and he must remain where he was, as he was sure the weather
would be fine, and that it was only a light haze over the moon; upon
which I went to the captain and gave my opinion. He agreed with me,
but did not like to take charge out of the pilots’ hands, saying he was
fearful, in getting under way, that the ship might get on shore should
she cast the wrong way. Now there was no fear of that, as a spring on
the cable would have cast her the right way, and the loss of an anchor
was of little consequence compared with the risk of losing the ship
and our lives.
Far be it from me to reflect upon Captain Dobree, who was a
good officer and seaman; and taking charge from a pilot was a great
responsibility; but when a pilot is guilty of a gross error, I should
never hesitate to take charge of the ship, if I knew I could do so with
safety, which was the case now. But it was neglected, and as I
foretold, the wind soon after backed round and blew dead upon the
shoal, so that we could not weather either end. At this time we were
at single anchor about two or three cable’s-lengths from the breakers,
blowing strong, and the sea getting up; at half cable; but let go
another anchor and veered to a whole cable on the former, and half
cable on the latter, bringing two anchors ahead. Sent topgallant
masts upon deck, and struck yards and topmasts; the wind
increasing to a gale, with a hollow sea and great strain upon the
cables. There was no alternative but to cut away the masts, which
was immediately done; but owing to an error of one of the officers,
who ordered the lanyards of the main stay to be cut before the
lanyards of one side of the main rigging, the main mast, in
consequence fell aft, and carried away the mizen mast, which stove
the boats on the quarters and did considerably damage to the upper
works; and some of the rigging caught fire, from the stove in the
cabin having the funnel knocked off; but this was soon got under,
and with great exertion the wreck was cleared. ‘And now, Master
Pilot,’ says I, ‘after getting us in this damnable situation, what next is
to be done?’ The son of a bitch could make me no answer; but the
junior pilot exclaimed ‘—— seize me if we sha’n’t be on the sands.’ I
could not help saying they deserved to be hanged as drowning was
too good for them.
I have already mentioned that we had Dutch troops on board
with their families, and of as much use as Castlereagh would have
been with the same number of his Lancers or Prancers.[140] The few
marines we had were worth a thousand of such live lumber. It was
ludicrous to see those Dutchmen coming upon deck with their hat
boxes, boots, trunks, flutes and music books, ready to go on shore,
when the sea was running mountains high, and a tremendous surf of
prodigious height on the sands close under our stern, and no chance
whatever, if the ship parted, of a soul being saved; which made
Captain Dobree observe to me, ‘Where ignorance is bliss ’tis folly to
be wise.’
About half-past ten A.M. we parted the best bower, and let go the
sheet anchor; and at the greatest risk—it was neck or nothing—
veered on the small bower to a whole, and half cable on the sheet,
which brought us very near the shoal but there was no help for it.
About twelve o’clock we observed that the small bower was stranded;
and at the moment when nothing but a miracle could save us, in a
terrific squall of thunder, lightning, hail, and rain, the wind suddenly
flew round and blew with violence off the shoal, which saved H. M.
ship Blonde from destruction. It soon after got moderate; we had an
excellent ship’s company, and in less than three hours we had jury
masts rigged and both anchors hove up—having saved the small
bower; made sail and anchored in a safer berth to await the tide.
About eleven P.M. we were surprised by a boat coming alongside
with four hands, who stated they belonged to a galliot that had struck
upon the tail of the shoal and had beat over into smoother water,
where she sunk. The crew had taken to the boat and were six hours
beating about before they got alongside of us, and thought we were a
floating light. As soon as the morning tide would allow we got under
way and followed some merchantmen—for I am certain the pilots did
not know the way without having a leader—and arrived at Sheerness
in the evening;
Ragged, and shabby, and all forlorn,
By wind and weather tattered and torn,
Occasioned by pilots who treated with scorn
The good advice that was given that morn;
For which a rope their necks should adorn,
The damnedest lubbers that ever were born.

Captain Dobree soon after left the ship to proceed with Sir
Home Popham and other captains to Russia, and I acted as captain
for several weeks until another was appointed. Having business on
shore, I wrote to the admiralty requesting to be superseded, which
after a little delay was granted, and Lieutenant Edwin James was
appointed in my room. I left the old Blonde and my worthy
messmates early in 1800.
I shall now relate a few anecdotes as they come to my memory.
When near the shoal I have just mentioned, our surgeon’s mate and
the ship’s cook were almost frightened out of their senses. The
former, who would fight any man, or face the devil as soon as let it
alone, was not equal to this; and when the junior pilot said, ‘——
seize me if we shan’t be on the sands,’ he clapped his hands and ran
down to the gun room, with his hair standing on end, crying out,
‘Lost! Lost! Lost!’—and then flew on deck again; and when the wind
shifted, he cut several capers and said ‘I’m a man again.’ As for the
cook, he had saved a sum of money by keeping shop on board and
selling things to the ship’s company. At the time the best bower
parted, he was on the forecastle in the greatest tribulation; says he,
‘Betty’ (meaning his wife, who was on board) ‘will go to a better
mansion, but I’m doubtful about myself.’ He had hardly made the
observation when the sea broke over the bows that threatened
destruction and with a faltering voice he said, ‘Liver me! Liver me!’—
meaning ‘Deliver me,’ but could not get the word out. ‘Damn your
liver, you croaking son of a bitch,’ says the captain of the forecastle.
‘Go into your coppers and be damned to you, and there you’ll be safe,
and don’t come barking here like a tanner’s dog.’ I was on the
forecastle with Captain Dobree at the time. He looked at me and for
my life I could not help laughing.
While at Sheerness we had two courts martial held on board of
[141]
us ; one on Lieutenant Brice, on charges brought against him by
Captain Charles Brisbane while on the South American station. The
charges being proved, he was sentenced to be dismissed the service
and rendered incapable of serving his Majesty, his heirs or
successors. This was most unfortunate for Lieutenant Brice, as his
commission to the rank of commander only waited the result of his
trial. The next was on Captain George Tripp, for the loss of the
Nassau, 64, on the Dutch Coast.[142] The court having heard all the
evidence came to the following conclusion:—That H.M. ship Nassau
was lost through the gross ignorance and inattention of Captain
Tripp, and that he did not set a good example to those under his
command; and for such conduct he was sentenced to be dismissed
from the service as unfit and unworthy, and rendered incapable of
serving his Majesty, his heirs or successors.
I promised (page 12) to speak of Pat Gibson when I came to the
Blonde. He was at this time (1799) purser of the Pallas, 38 (formerly
the Minerva), having given up the Princess Royal as too great an
undertaking for his age, being, as he told me, eighty. The Pallas being
alongside the same hulk, we were constant visitors. As every
circumstance, however trifling, may be interesting, I shall relate a
few anecdotes. Gibson was a tall raw-boned Irishman from the
county of Tipperary; very powerful, with an Herculean grasp, and
woe betide those who got into his clutches if roused to anger. He was
a very jovial companion, droll in his manner, full of anecdote, and
sung in the Irish language, of which he was a perfect master. He used
to go on shore to bring off the drunken Irish who had stayed above
their time, and I remember his saying to me, ‘Arrah, don’t you think,
my dear fellow, that it’s a hard thing that nobody can manage those
spalpeens but an ould man like me, now eighty years of age? Och, By
the Holy Father, how I knocked their heads together, and left the
mark of my fist upon their ugly podreen faces, bad luck to them.’
He was at the taking of Quebec and was one of those that
assisted in carrying General Wolfe off the field when mortally
wounded. His account of the battle was very interesting, and in it he
fought most manfully. It was amusing to see him sitting in his cabin
with his legs stretched outside the door singing Irish songs. The
steward once interrupted him, for which he got a thump on the back
that sent him the length of the gunroom, Pat saying, ‘To hell wid you!
take dat till the cows come home.’ There was a countryman of his by
the name of Fegan, who, in the American war, was sent by Sir John
Fielding (the celebrated magistrate of Bow Street) on board the
Conquistador, 60, then lying as a guard-ship at the Nore with
Admiral Roddam’s flag. This Fegan was a shrewd, keen fellow, and
made a song on being sent on board of a man of war, and Gibson was
very fond of singing it. I only remember a few verses:—
The beginning of the war they hobbled poor Fegan,
And sent him on board of the Conquistador;
That floating old gin shop, who struck upon her beef bones,
While laying as a guard-ship near the buoy of the Nore.

When first they lugged him before Justice Fielding,[143]


Fegan thus to him did say:
You may be damned, you old blind b——,
I will be back again before Christmas day.

By my sowl, Mr. Fegan, you are a fine fellow,


It’s you that have done the king much wrong;
Call Kit Jourdan, the master at arms, sir,
And put Mr. Fegan in double irons strong.

Step here, boatswain’s mate, and give him a starting;


Says the first lieutenant it’s always my way;
And you shall have many before the day of parting—
I think, Mr. Fegan, you mentioned Christmas day.

Etc., etc., etc.

When I called on him about three months before his death he


told me he was then on his last legs; that he had enjoyed an
uninterrupted state of health for upwards of ninety years; that he
never had the headache, rheumatism, toothache or spasms, and that
he had nothing to do with doctors’ bottles with collars round their
necks, and look, says he, if you can find any of that craft on my
chimney-piece. Before I close I must give another song of his:—
There was a wedding at Baltimore,
Of three score people lacking of four;
And you’re kindly welcome, welcome all,
And you’re welcome, gramachree, welcome all.

The priest of the parish got up at the dawn,


To marry brisk Flemming to sweet Susan Bawn;
And you’re kindly welcome, welcome all,
And you’re welcome, gramachree, welcome all.

There was Tyghe, and Dermot, and Madam Shevaun,


And they all rode on a long-tailed gar-ron;[144]
And you’re kindly welcome, welcome all,
And you’re welcome, gramachree, welcome all.

There was sneezing galore, with full madders[145] of ale,


Which made maidens stagger and men for to reel;
And you’re kindly welcome, welcome all,
And you’re welcome, gramachree, welcome all.

Potatoes and herrings must please the men,


But madam the bride, she must have a fat hen;
And you’re kindly welcome, welcome all,
And you’re welcome, gramachree, welcome all.

There was long kail, and pottage, with good pishochbey,[146]


And the rarest colcannon[147] that e’er you did see;
And you’re kindly welcome, welcome all,
And you’re welcome, gramachree, welcome all.

When the feasting was o’er, from the room she was led,
Where they lay head and points as if they were dead;
And you’re kindly welcome, welcome all,
And you’re welcome, gramachree, welcome all.

· · · · ·

Our master, Henry Webb, was a very worthy fellow, but had
strange fancies. When we were going from the Downs to Portsmouth,
and about three leagues to the southward of Beachy Head, he had the
first watch, and having after supper taken his drop, he dropped
asleep while sitting on the gun-carriage and had a dream that the
ship was on shore. Up he started and ran into the captain, who had
gone to bed, and called out, ‘Get up, sir, we are all lost.’ The captain
jumped out of bed and went upon deck in his shirt, and ordered the
hands to be turned up, and sent for me. I flew up with only my
trowsers on, found everything in confusion, and I really thought that
madness had seized the whole. ‘Put the ship about, sir, immediately,’
says the captain. This I complied with, and when on the other tack I
asked him if anything was the matter. ‘Mr. Webb, sir,’ says he, ‘must
be sent to the madhouse.’ I confess I was not well pleased, as I had
the middle watch and this happened at six bells, so I had an hour
more than I expected to trudge the deck. I should have stated that
the wind was westerly and we were beating down Channel with a
moderate breeze. The captain was much inclined to bring Master
Webb to a court martial, but we interceded for him and the business
was looked over, but he never heard the last of this, and would
frequently be greeted with the well-known words, ‘Turn out, we are
all lost’—a compliment he could well dispense with.
He gave us a droll account that when at Lisbon he missed the
boat that was to take the officers off in the evening who were on
shore upon leave, and was engaging a shore boat for that purpose;
but suspecting from something the boatmen were saying that their
intention was to murder him, he took to his heels and hid under
some logs in the neighbourhood of Bull Bay and remained there all
night in the greatest terror. When he sallied out in the morning he
was covered with filth of a yellow hue and appeared at a distance as if
he had been dipped in Pactolus! His fright was so great that he was
not aware of the bed of roses he had reposed on for so many hours,
until he started in the morning with blushing honours thick upon
him.
On another occasion, coming up in a small fishing boat from
Sheerness to Chatham, he heard two of the men whispering, which
he imagined was about himself, and when making a tack and near
the mud, out he jumped and began to crawl upon his hands and
knees as fast as he could for dry land. The poor fishermen, not
knowing what to make of such conduct, ran the boat on the mud and
two of them went after him, but to no purpose, it being dark. They
called repeatedly, but got no answer from Webb, who was making off
in terror and dismay; and what alarmed him more was hearing the
men say, ‘D’ye see him now? Where the hell can he be got to? He
must be hereabouts.’ At last he got out of the mud and set off for
Chatham in a nice pickle, and told his tale; but the boat had arrived
before him and the men in great tribulation had given their version,
being fearful of prosecution, expecting that Webb was smothered or
drowned; and glad enough they were when he arrived at Chatham
and also to join in the laugh against him. One of the fishermen
happened to know him by sight and where he lived, and by that
means it got publicity.
In cases like this, and where ghosts were introduced, Webb’s
courage would be put to the test; but in every other respect he was as
brave as a lion. While at the Passage of Waterford, he had a dispute
with our second lieutenant, and a challenge was the consequence,
and they asked me leave to go on shore. As I had the greatest
friendship for them both, I refused their request, and went below to
the gunroom. Soon after one of the midshipmen came down and
informed me they were going out of the ship. Up I went and found
them in the jolly boat just shoved off. ‘Come back,’ says I,
‘immediately, or I’ll make the sentry fire.’ On their return I told them
if they did not make it up instantly, I would try them by a court
martial for going out of the ship contrary to orders and taking the
boat. This had the desired effect, and I had the pleasure of making up
the dispute between two as good fellows as ever lived.
The second lieutenant (Jack Derby) was a noisy droll fellow,
always keeping the mess in a roar of laughter. The first day he joined
the ship we had roast beef for dinner, and when brought to table it
was little better than half done by the neglect of our black cook. Now
this cook’s name was Jack Derby also, whom I sent for, and calling
him up to the head of the table close by Lieutenant Jack Derby, says
I, ‘I am sorry, sir, you should have such a dinner, particularly the first
day of your coming on board; but you have to thank that black son of
a bitch, Jack Derby’—an emphasis on the word—‘whose grog shall be
stopped for such neglect.’ ‘Don’t mention it, sir,’ says he laughing; ‘I
shall make a very good dinner, and suppose my name will be inserted
on the ship’s books as Jack Derby the Second.’
While lying off Lymington our launch was sent to Portsmouth
yard for stores, and Derby was sent in her. On her return, our purser
(Huish) took a passage. On leaving the harbour the weather was
moderate, but soon after came on to blow from the westward. Now
the purser was very fearful in a boat, and Derby carried more sail
than he ought, on purpose to alarm him. From the harbour to
Lymington, the distance is twenty-six miles, and the wind being dead
on end they had to beat all the way. Sometimes the boat would be
gunwale under, and Huish, terrified almost to death, would every
moment rise from his seat and fall again, exclaiming, ‘Jesus, Jenny,
Jesus, Jenny’ (common words of his when things went wrong), and
cursed the hour he was fool enough to trust himself with Derby, and
if it pleased Providence to spare him now he would never put his foot
in a boat with him even in a calm. But his troubles were not yet over,
for in getting into the Fiddler’s Race near Gurnet Point, on the Isle of
Wight side, with the tide under their lee, there was such a sea
breaking that the launch was nearly swamped, and Derby seriously
repented his joke; while Huish in despair repeatedly ejaculated,
‘Orontes’ bark, Orontes’ bark will be our fate.’ (See Aeneid [i. 117]).
[148]
However, they got safe on board and created much amusement
in the account Huish gave of Derby’s wickedness.
Being ordered to embark the 23rd regiment foot for Guernsey,
and after going through the Needles in the evening, it came on thick
weather in the first watch; and about eleven the wind, at SE, began to
blow a hurricane, with snow so thick that we could not see half the
length of the ship. We sent topgallant yards and topgallant masts
upon deck, and hove the ship to under storm staysails. The topsails
and courses were frozen as hard as board, and being short of
complement it took nearly the whole of the middle watch before they
could be furled. One of our main topmen was frozen and died soon
after. The officers were also aloft, and all hands suffered most
dreadfully. I was speaking to the man at the wheel when a sheet of
ice fell out of the mizen top and knocked both of us down. It gave me
a severe blow on the shoulder and the other a staggering thump on
the back. I was so benumbed when I got below that I had hardly life
in me. The officers of the 23rd made me swallow hot brandy and
water, and I went to bed, where I had not been above half an hour
before all hands were called again, and I was obliged to go on deck.
The fact was the fore topsail had got loose and blew to rags, and the
main topsail was nearly following its example, but stopped in time,
and we had to bend another fore topsail in this cruel weather.
Towards morning it cleared up and got moderate. During the whole
course of my life I never suffered so much as I did on that dreadful
night. However, we got safe into Guernsey and landed our soldiers.
The officers were a glorious set of fellows, and sorry I am that I
cannot find any of their names on the list.
The last time we were at the Passage of Waterford was passed
very agreeably. I had a cousin (the son of the late Alderman Bates of
Waterford) who had an estate in the neighbourhood. He used to send
horses and a carriage for the officers of our mess, who were
frequently at his house. He was field officer of the district and kept a
great deal of company, and gave many parties in honour of the old
Blonde. On one occasion he came on board to invite us to an evening
party, when he and Jack Derby got into conversation, and at last got
so drunk that it was evening before they got sober enough to leave
the ship. It was then time to go, and off they started, Derby in full
uniform. When the boat landed, he, with all the politeness
imaginable, wanted to hand Bates out. This Bates declined. ‘Then,’
says Jack, ‘we’ll go together.’ Now the gang board was hardly broad
enough for two, and the moment they stepped upon it over they went
where the water was four feet deep and got a fine ducking. Derby
would not return to the ship, but, mounting a horse belonging to
Bates, set off in his wet clothes to meet the party, and there Bates
dressed him in regimentals, and a precious figure he cut. We passed
a very pleasant evening, there being near seventy present. One of the
ladies sung the beautiful air of ‘Eileen Aroon’ in Irish—a translation
of which I met with a few years ago and give it as follows:—
I’ll love thee evermore,
Eileen aroon.
I’ll bless thee o’er and o’er,
Eileen aroon.
Oh, for thy sake I’ll tread
Where the plains of Mayo spread,
By hope still fondly led,
Eileen aroon.

Oh! how may I gain thee,


Eileen aroon?
Shall feasting entertain thee,
Eileen aroon?
I would range the world wide,
With love alone to guide,
To win thee for my bride,
Eileen aroon.

Then wilt thou come away,


Eileen aroon?
Oh! wilt thou come or stay,
Eileen aroon?
Oh yes! oh yes! with thee
I will wander far and free,
And thy only love shall be,
Eileen aroon.

A hundred thousand welcomes


Eileen aroon.
A hundred thousand welcomes,
Eileen aroon.
Oh! welcome evermore,
With welcomes yet in store,
Till love and life are o’er,
Eileen aroon.
We had a fidgety and crabbed commodore (Captain Stevenson
of the Europa, 50) who neither enjoyed pleasure himself nor would
let anyone else do so: who kept Blue Peter flying the fortnight we
remained, which said No! to every invitation to the city.
In going from Portsmouth to the Downs we gave a passage to an
assistant surgeon, red hot from the land of cakes, who had never
been on board of a man of war, and had now an appointment to a
gun vessel. Seeing that he was a complete greenhorn, we took him
into our mess that the midshipmen should not make a butt of him,
for which he was very thankful. On leaving the ship in the Downs, he
took the surgeon aside, saying, ‘You have all been very kind to me,
particularly the purser, and I would wish to make him some
acknowledgment. D’ye think if I gave him three pounds of cheese!!! it
would satisfy him?’ After he landed at Deal he put up at the Three
Kings. Captain Dobree, happening to go into the coffee room,
observed him in one of the boxes, and hearing him ask the waiter
what there was for dinner, stayed to hear the result. The bill of fare
being given him, he ordered an apple pie, which was brought him
made in a good-sized dish. This he devoured in a short time, and
ordered the fellow to bring him another, which he demolished also,
and then rang the third time and asked him if he had any more of

You might also like