Instant Ebooks Textbook Mastering JavaScript Single Page Application Development 1. Edition Klauzinski Download All Chapters
Instant Ebooks Textbook Mastering JavaScript Single Page Application Development 1. Edition Klauzinski Download All Chapters
com
https://ebookname.com/product/mastering-javascript-single-
page-application-development-1-edition-klauzinski/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/beginning-windows-store-
application-development-html-and-javascript-edition-burns/
https://ebookname.com/product/beginning-ios-application-
development-with-html-and-javascript-1st-edition-richard-
wagner-2/
https://ebookname.com/product/beginning-ios-application-
development-with-html-and-javascript-1st-edition-richard-wagner/
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/
https://ebookname.com/product/blender-for-animation-and-film-
based-production-1st-edition-michelangelo-manrique/
https://ebookname.com/product/the-ultimate-sourcebook-of-
knitting-and-crochet-stitches-1st-edition-harmony-guides/
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
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.
ISBN 978-1-78588-164-0
www.packtpub.com
Credits
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.
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.
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.
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."
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: [
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."
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.
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:
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.
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.
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.
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.
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
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.
To update your devDependencies and save the new version numbers, you can enter the
following from the command line:
$ npm update --save-dev
To update all globally installed NPM packages to their latest versions, run npm update
with the -g option:
$ npm update -g
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.
$ 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.
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"
}
}
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.
[ 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.
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 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.