SlideShare a Scribd company logo
Practical Node js Building Real World Scalable
Web Apps 1st Edition Azat Mardan (Auth.)
download
https://ebookgate.com/product/practical-node-js-building-real-
world-scalable-web-apps-1st-edition-azat-mardan-auth/
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats
Professional Node js Building Javascript Based Scalable
Software 1st Edition Pedro Teixeira
https://ebookgate.com/product/professional-node-js-building-
javascript-based-scalable-software-1st-edition-pedro-teixeira/
Building Serverless Web Applications Develop scalable
web apps using the Serverless Framework on AWS 1st
Edition Diego Zanon
https://ebookgate.com/product/building-serverless-web-
applications-develop-scalable-web-apps-using-the-serverless-
framework-on-aws-1st-edition-diego-zanon/
Node js Recipes 1st Edition Cory Gackenheimer (Auth.)
https://ebookgate.com/product/node-js-recipes-1st-edition-cory-
gackenheimer-auth/
Building Scalable Web Sites Building Scaling and
Optimizing the Next Generation of Web Applications 1st
Edition Cal Henderson
https://ebookgate.com/product/building-scalable-web-sites-
building-scaling-and-optimizing-the-next-generation-of-web-
applications-1st-edition-cal-henderson/
Programming JavaScript Applications Robust Web
Architecture with Node HTML5 and Modern JS Libraries
1st Edition Eric Elliott
https://ebookgate.com/product/programming-javascript-
applications-robust-web-architecture-with-node-html5-and-modern-
js-libraries-1st-edition-eric-elliott/
Beginning Node js 1st Edition Basarat Ali Syed (Auth.)
https://ebookgate.com/product/beginning-node-js-1st-edition-
basarat-ali-syed-auth/
Smashing Node js JavaScript everywhere 2nd Edition
Guillermo Rauch
https://ebookgate.com/product/smashing-node-js-javascript-
everywhere-2nd-edition-guillermo-rauch/
Head First HTML5 Programming Building Web Apps with
JavaScript 1st Edition Eric T Freeman
https://ebookgate.com/product/head-first-html5-programming-
building-web-apps-with-javascript-1st-edition-eric-t-freeman/
Node Web Development Second Edition David Herron
https://ebookgate.com/product/node-web-development-second-
edition-david-herron/
Practical Node js Building Real World Scalable Web Apps 1st Edition Azat Mardan (Auth.)
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
v
Contents at a Glance
About the Author����������������������������������������������������������������������������������������������������������������xv
About the Technical Reviewer������������������������������������������������������������������������������������������xvii
Acknowledgments�������������������������������������������������������������������������������������������������������������xix
Introduction�����������������������������������������������������������������������������������������������������������������������xxi
Chapter 1: Setting up Node.js and Other Essentials
■
■ ����������������������������������������������������������1
Chapter 2: Using Express.js 4 to Create Node.js Web Apps
■
■ 
���������������������������������������������33
Chapter 3: TDD and BDD for Node.js with Mocha
■
■ ������������������������������������������������������������57
Chapter 4: Template Engines: Jade and Handlebars
■
■ �������������������������������������������������������71
Chapter 5: Persistence with MongoDB and Mongoskin
■
■ 
�������������������������������������������������103

Chapter 6: Using Sessions and OAuth to Authorize and Authenticate
■
■
Users in Node.js Apps
����������������������������������������������������������������������������������������������������129
Chapter 7: Boosting Your Node.js Data with the Mongoose ORM Library
■
■ ���������������������149
Chapter 8: Building Node.js REST API Servers with Express.js and Hapi
■
■ ����������������������173
Chapter 9: Real-Time Apps with WebSocket, Socket.IO, and DerbyJS
■
■ ��������������������������195
Chapter 10: Getting Node.js Apps Production Ready
■
■ ����������������������������������������������������215
Chapter 11: Deploying Node.js Apps
■
■ �����������������������������������������������������������������������������243
Chapter 12: Publishing Node.js Modules and Contributing to Open Source
■
■ 
������������������261
Index���������������������������������������������������������������������������������������������������������������������������������269
xxi
Introduction
There are more and more books and online resources being published that cover Node.js basics (e.g., how-to’s of
Hello World and simple apps). For the most part, these tutorials rely on core modules only or maybe one or two
Node Package Manager (NPM) packages. This “sandbox” approach of tutorials is easy and doesn’t require many
dependencies, but it can’t be further from the actual Node.js stack. This is especially true with Node.js, the core of
which—by design—is kept lean and minimal. At the same time, the vast “userland” (i.e., NPM) provides an ecosystem
of packages/modules to serve specific granular purposes. Therefore, there is a need to show effectively how Node.js
is used in the industry and to have it all in one place—the all-encompassing practical resource that can be used as a
learning tool, a code cookbook, and a reference.
What This Book Is
Practical Node.js: Building Real-World Scalable Web Apps is a hands-on manual for developing production-ready
web applications and services by leveraging the rich ecosystem of Node.js packages. This is important because real
applications require many components, such as security, deployment, code organization, database drivers, template
engines, and more. This is why we include extensive 12-chapter coverage of third-party services, command-line tools,
NPM modules, frameworks, and libraries.
Just to give you some idea, Practical Node.js is a one-stop place for getting started with Express.js 4, Hapi.js,
DerbyJS, Mongoskin, Mongoose, Everyauth, Mocha, Jade, Socket.IO, TravisCI, Heroku, Amazon Web Services (AWS),
and many others. Most of these items are vital for any serious project.
In addition, we create a few projects by building, step by step, from a straightforward concept to a more
complicated application. These projects can also serve as a boilerplate for jump-starting your own development
efforts. Also, the examples show industry best practices to help you avoid costly mistakes.
Last but not least, many topics and chapters serve as a reference to which you can always return later when
you’re faced with a challenging problem.
Practical Node.js aims to save you time and make you a more productive Node.js programmer!
What You’ll Learn
Practical Node.js takes you from an overview of JavaScript and Node.js basics, installing all the necessary modules to
writing and deploying web applications, and everything in between. We cover libraries including, but not limited to,
Express.js 4 and Hapi.js frameworks, Mongoskin and the Mongoose object-relational mapping (ORM) library for the
MongoDB database, Jade and Handlebars template engines, OAuth and Everyauth libraries for OAuth integrations,
the Mocha testing framework and Expect test-driven development/behavior-driven development language, and the
Socket.IO and DerbyJS libraries for WebSocket real-time communication.
■ Introduction
xxii
In the deployment chapters (10 and 11), the book covers how to use Git and deploy to Heroku, as well as
examples of how to deploy to AWS, daemonize apps, and use Nginx, Varnish Cache, Upstart, init.d, and the forever
module.
The hands-on approach of this book walks you through iterating on the Blog project in addition to many other
smaller examples. You’ll build database scripts, representational state transfer (RESTful) application programming
interfaces (APIs), tests, and full-stack apps all from scratch. You’ll also discover how to write your own Node.js
modules and publish them on NPM.
Practical Node.js will show you how to do the following:
Build web apps with Express.js 4, MongoDB, and the Jade template engine
•
Use various features of Jade and Handlebars
•
Manipulate data from the MongoDB console
•
Use the Mongoskin and Mongoose ORM libraries for MongoDB
•
Build REST API servers with Express.js 4 and Hapi.js
•
Test Node.js web services with Mocha, Expect, and TravisCI
•
Use token and session-based authentication
•
Implement a third-party (Twitter) OAuth strategy with Everyauth
•
Build WebSocket apps using Socket.IO and DerbyJS libraries
•
Prepare code for production with Redis, Node.js domains, and the cluster library using tips
•
and best practices
Deploy apps to Heroku using Git
•
Install necessary Node.js components on an AWS instance
•
Configure Nginx, Upstart, Varnish, and other tools on an AWS instance
•
Write your own Node.js module and publish it on NPM
•
You already know what Node.js is; now, learn what you can do with it and how far you can take it.
What This Book Is Not
Although the entire first chapter is dedicated to installations and a few important differences between Node.js and
browser JavaScript, we didn’t want to dilute the core message of making production-ready apps, or make
Practical Node.js even larger and more convoluted. Therefore, the book is not a beginner’s guide and there is no
extensive immersion into the inner workings of the Node.js platform and its core modules.
We also can’t guarantee that each component and topic are explained to the extent you need, because the nature
of your project might be very specific. Most chapters in the book help you to get started with the stack. There is simply
no realistic way to fit so many topics in one book and cover them comprehensively.
Another caveat of this book (or virtually any other programming book) is that the versions of the packages we
use will eventually become obsolete. Often, this isn’t an issue because, in this book, versions are stated and locked
explicitly. So no matter what, the examples will continue to work with our versions.
Even if you decide to use the latest versions, in many cases this still might not be an issue, because essentials
remain the same. However, if you go this off-path route, once in a while you might be faced with a breaking change
introduced by the latest versions.
■ Introduction
xxiii
Who Can Benefit from This Book
Practical Node.js is an intermediate- to advanced-level book on programming with Node.js. Consequently, to get the
most out of it, you need to have prior programming experience and some exposure to Node.js. We assume readers’
prior knowledge of computer science, programming concepts, web development, Node.js core modules, and the
inner workings of HTTP and the Internet.
However, depending on your programming level and ability to learn, you can fill in any knowledge gaps very
quickly by visiting links to official online documentations and reading external resources referenced in this book. Also,
if you have a strong programming background in some other programming language, it would be relatively easy for
you to start Node.js development with Practical Node.js.
As mentioned earlier, Practical Node.js is written for intermediate and advanced software engineers. For this
reason, there are three categories of programmers who can benefit from it the most:
1. Generalist or full-stack developers including development operation (DevOps) and quality
assurance (QA) automation engineers
2. Experienced front-end web developers with a strong background and understanding of
browser JavaScript
3. Skilled back-end software engineers coming from other languages such as Java, PHP, and
Ruby, who don’t mind doing some extra work get up to speed with the JavaScript language
Source Code
Learning is more effective when we apply our knowledge right away. For this reason, virtually every chapter in
Practical Node.js ends with a hands-on exercise. For your convenience, and because we believe in open source and
transparency, all the book’s examples are available publicly (i.e., free of charge) for exploration and execution on
GitHub at https://github.com/azat-co/practicalnode.
Errata and Contacts
If you spot any mistakes or typos (and I’m sure you will), please open an issue or, even better, fix it and make a pull
request to the GitHub repository of the book’s examples at https://github.com/azat-co/practicalnode. For all
other updates and contact information, the canonical home of Practical Node.js on the Internet is
http://practicalnodebook.com.
Notation
This book follows a few formatting conventions. Code is in monospace font—for example, var book = {name:
'Practical Node.js'}; . If the code begins with $, this code is meant to be executed in the terminal/command line.
However, if the code line starts with , the code is meant for the virtual environment (a.k.a., console—either for
Node.js or MongoDB). If the Node.js module name is in code font, this is the NPM name and you can use it with NPM
and the require() method, such as superagent.
■ Introduction
xxiv
Why You Should Read This Book
Practical Node.js was designed to be one stop for going from Hello World examples to building apps in a professional
manner. You get a taste of the most widely used Node.js libraries in one place, along with best practices and
recommendations based on years of building and running Node.js apps in production. The libraries covered in
Practical Node.js greatly enhance the quality of code and make you more productive. Also, although the material in
this book is not groundbreaking, the convenience of the format saves hours of frustration researching the Internet.
Therefore, Practical Node.js is here to help you to jump-start your Node.js development!.
1
Chapter 1
Setting up Node.js and Other
Essentials
As with many technologies, it’s vital to have the proper foundation set up first, before moving on to solving more
complex problems. In this chapter, we cover the following:
Node.js and (NPM) Node Package Manager installation
•
Node.js script launches
•
Node.js syntax and basics
•
Node.js integrated development environments (IDEs) and code editors
•
Awareness of file changes
•
Node.js program debugging
•
Installing Node.js and NPM
Although your operating system (OS) might have Node.js installed on it already, you should update to at least 0.10.x.
In the following subsection, we examine a few different approaches to installing Node.js:
• One-click installers: probably the easiest and fastest way to get started with the platform
• Installing with HomeBrew or MacPorts: straightforward installation for Max OS X users
• Installing from a tar file: an alternative installation from an archive file
• Installing without sudo: the best way to avoid needing sudo (admin rights) when using the
node and npm commands
• Installing from a Git repo: an option for advanced developers who need the latest version
and/or contribute to the project
• Multiversion setup with Nave: a must-have for developers contributing to projects that use
different Node.js versions
• Multiversion setup with Node Version Manager (NVM): alternative to Nave (see previous entry)
Chapter 1 ■ Setting up Node.js and Other Essentials
2
One-Click Installers
First, let’s go to http://nodejs.org and download a one-click installer for your OS (Figure 1-1) by clicking on the
Install button. Don’t choose binaries or source code unless you know what to do with them or your OS is not present
there (i.e., not Windows or Mac).
Figure 1-1. One-click installers for Node.js
The installers come with NPM (Node Package Manager)— an important tool for managing dependencies.
If there’s no installer for your OS (page http://nodejs.org/download/), you can get the source code and
compile it yourself (Figure 1-2).
Chapter 1 ■ Setting up Node.js and Other Essentials
3
Note
■
■ For older Mac OS X machines, you can pick 32-bit versions.
Installing with HomeBrew or MacPorts
If you already have HomeBrew (brew) installed, run the following in a straightforward manner:
$ brew install node
$ brew install npm
Similarly, for MacPorts, run
$ sudo port install nodejs
Figure 1-2. Multiple options for downloading
Chapter 1 ■ Setting up Node.js and Other Essentials
4
If your Mac OS X does not have HomeBrew, go to http://brew.sh/ or install it with the following command:
$ ruby -e $(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)
Installing from a Tar File
To install from a tar file (which is type of archive), set up a folder for the latest Node.js as follows:
$ echo 'export PATH=$HOME/local/bin:$PATH'  ~/.bashrc
$ . ~/.bashrc
$ mkdir ~/local
$ mkdir ~/node-latest-install
$ cd ~/node-latest-install
Note
■
■  Advanced users who choose to make their own Node.js builds need to have certain compilers installed first. For
more information, refer to the official documentation (https://github.com/joyent/node/wiki/Installation).
Download the tar file with CURL and unpack it:
$ curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
$ ./configure --prefix=~/local
Build Node.js and install it:
$ make install
$ curl https://npmjs.org/install.sh | sh
Tip
■
■  If you find yourself getting errors when trying to install the module globally via NPM ($ npm install -g
packagename), reinstall Node.js and NPM with the “Installing Without sudo” solution below to eliminate the need
to use sudo with the installation command. For more solutions for advanced users, there’s a Gist from Isaac Z. Schlueter:
https://gist.github.com/isaacs/579814.
Installing Without sudo
Sometimes, depending on your configuration, NPM asks users for sudo— root user permissions. To avoid using sudo,
advanced developers can use the following::
$ sudo mkdir -p /usr/local/{share/man,bin,lib/node,include/node}
$ sudo chown -R $USER /usr/local/{share/man,bin,lib/node,include/node}
Note
■
■  Please be sure you are comfortable with the functionality of the chown command before you run it.
Chapter 1 ■ Setting up Node.js and Other Essentials
5
Then, proceed with a normal installation:
$ mkdir node-install
$ curl http://nodejs.org/dist/node-v0.4.3.tar.gz | tar -xzf - -C node-install
$ cd node-install/*
$ ./configure
$ make install
$ curl https://npmjs.org/install.sh | sh
Installing from a Git Repo
If you want to use the latest core Node.js code, and maybe even contribute to the Node.js and NPM projects, it’s possible
to build the installation from the cloned Git repo. (This step requires Git. To install it, go to http://git-scm.com/
and click Download.) For basic Git commands, refer to Chapter 11, where we explore deployment; otherwise, do the
following:
1. Make the folders and add the path:
$ mkdir ~/local
$ echo 'export PATH=$HOME/local/bin:$PATH'  ~/.bashrc
$ . ~/.bashrc
To clone the original Node.js repo from Joyent (alternatively, you can fork it and clone your own repository),
do the following:
$ git clone git://github.com/joyent/node.git
$ cd node
$ ./configure --prefix=~/local
2. Make the build:
$ make install
$ cd ..
3. Repeat for NPM:
$ git clone git://github.com/isaacs/npm.git
$ cd npm
$ make install
For a more cutting-edge NPM version, use
$ make link
Multiversion Setup with Nave
If you plan to run multiple versions of Node.js, use Nave (https://github.com/isaacs/nave), which is a virtual
environment for Node.js. First, make a folder:
mkdir ~/.nave
cd ~/.nave
Chapter 1 ■ Setting up Node.js and Other Essentials
6
Then, download Nave and set the link to the PATH-ed folder:
$ wget http://github.com/isaacs/nave/raw/master/nave.sh
$ sudo ln -s $PWD/nave.sh /usr/local/bin/nave
An example of switching to Node.js version 0.4.8 with Nave in a virtual environment is as follows:
$ nave use 0.4.8
To use NPM in this particular virtual environment, use
$ curl https://npmjs.org/install.sh | sh
It is now possible to install something via NPM:
$ npm install express
Last, exit the virtual environment with
exit
More approaches to install Node.js and NPM are in gist (https://gist.github.com/isaacs/579814).
Multiversion Setup with NVM
Another option to Nave is NVM—Node Version Manager (GitHub, https://github.com/creationix/nvm). Install
NVM as follows:
$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh
or
$ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
Then, harness NVM’s install:
$ nvm install 0.10
To switch to the 0.10 version, apply the use command. For example:
$ nvm use 0.10
Alternative Multiversion Systems
Alternatives to Nave and NVM include the following:
neco
• (https://github.com/kuno/neco)
n
• (https://github.com/visionmedia/n)
Chapter 1 ■ Setting up Node.js and Other Essentials
7
Checking the Installation
To test your installation, run the following commands in your Terminal app (command line cmd.exe in Windows):
$ node -v
$ npm -v
You should see the latest versions of Node.js and NPM that you just downloaded and installed, as shown in
Figure 1-3.
Figure 1-3. Checking Node.js and NPM installations
That’s it! You now have Node.js and NPM installed, and you should be ready to dig deeper into using the platform.
The simplest way to run Node.js is through its virtual environment, which is often called read–eval–print–loop, or REPL.
Node.js Console (REPL)
Like most platforms/languages (e.g., Java, Python, Ruby, and PHP), Node.js comes with a virtual environment: REPL.
Using this shell program, we can execute pretty much any Node.js/JavaScript code. It’s even possible to include modules
and work with the file system! Other REPL use cases involve controlling nodecopters (http://nodecopter.com/)
and debugging remote servers (more about this in Chapter 10). To start the console, run the following command in
your terminal:
$ node
Chapter 1 ■ Setting up Node.js and Other Essentials
8
The prompt should change from $ to  (or something else, depending on your shell). From this prompt, we can
run any JavaScript/Node.js (akin to the Chrome Developer Tools console) we want. For example:
 1+1
 Hello+ +World
 a=1;b=2;a+b
 17+29/2*7
 f = function(x) {return x*2}
 f(b)
The result of the previous snippet is shown in Figure 1-4.
Figure 1-4. Executing JavaScript in Node.js REPL
There are slight deviations in ECMAScript implementations in Node.js and browsers such as the Chrome
Developer Tools console. For example, {}+{} is '[object Object][object Object]' in Node.js REPL, whereas the
same code is NaN in the Chrome console because of the automatic semicolon insertion (ASI) feature. However, for the
most part, Node.js REPL and the Chrome/Firefox consoles are similar.
Launching Node.js Scripts
To start a Node.js script from a file, simply run $ node filename—for example, $ node program.js. If all we need is
a quick set of statements, there’s a -e option that allows us to run inline JavaScript/Node.js—for example, $ node -e
console.log(new Date());.
Chapter 1 ■ Setting up Node.js and Other Essentials
9
If the Node.js program uses environmental variables, it’s possible to set them right before the node command.
For example:
$ NODE_ENV=production API_KEY=442CC1FE-4333-46CE-80EE-6705A1896832 node server.js
Preparing your code for production is discussed later in Chapter 10.
Node.js Basics and Syntax
Node.js was built on top of the Google Chrome V8 engine and its ECMAScript, which means most of the Node.js
syntax is similar to front-end JavaScript (another implementation of ECMAScript), including objects, functions,
and methods. In this section, we look at some of the most important aspects; let’s call them Node.js/JavaScript
fundamentals:
Loose typing
•
Buffer—Node.js super data type
•
Object literal notation
•
Functions
•
Arrays
•
Prototypal nature
•
Conventions
•
Loose Typing
Automatic typecasting works well most of the time. It’s a great feature that saves a lot of time and mental energy!
There are only a few types of primitives:
String
•
Number (both integer and real)
•
Boolean
•
Undefined
•
Null
•
RegExp
•
Everything else is an object (i.e., mutable keyed collections, read Stackoverflow on “What does immutable
mean?”
,1
if in doubt).
Also, in JavaScript, there are String, Number, and Boolean objects that contain helpers for the primitives,
as follows:
'a' === new String('a') //false
but
1
http://stackoverflow.com/questions/3200211/what-does-immutable-mean
Chapter 1 ■ Setting up Node.js and Other Essentials
10
'a' === new String('a').toString() //true
or
'a' == new String('a') //true
By the way, == performs automatic typecasting whereas === does not.
Buffer—Node.js Super Data Type
Buffer is a Node.js addition to four primitives (boolean, string, number, and RegExp) and all-encompassing objects
(array and functions are also objects) in front-end JavaScript. Think of buffers as extremely efficient data stores. In
fact, Node.js tries to use buffers any time it can, such as when reading from file systems and when receiving packets
over the network.
Object Literal Notation
Object notation is super readable and compact:
var obj = {
color: green,
type: suv,
owner: {
...
}
}
Remember, functions are objects:
var obj = function () {
this.color: green,
this.type: suv,
this.owner: {
...
}
}
Functions
In Node.js (as well as in JavaScript), functions are first-class citizens, and we treat them as variables, because they are
objects! Yes, functions can even have properties/attributes. First, let’s learn how to define a function.
Define/Create a Function
The three most common ways to define/create a function are to use a named expression, an anonymous expression
assigned to a variable, or both. The following is an example of a named expression:
function f () {
console.log('Hi');
return true;
}
Chapter 1 ■ Setting up Node.js and Other Essentials
11
An anonymous function expression assigned to a variable looks as follows (note that it must precede the
invocation, because the function is not hoisted, unlike the previous example):
var f = function () {
console.log('Hi');
return true;
}
The following is an example of both approaches:
var f = function f () {
console.log('Hi');
return true;
}
A function with a property (remember, functions are just objects that can be invoked/initialized) is as follows:
var f = function () {console.log('Boo');}
f.boo = 1;
f(); //outputs Boo
console.log(f.boo); //outputs 1
Note
■
■  The return keyword is optional. When it is omitted, the function returns undefined on invocation.
Pass Functions as Parameters
JavaScript treats functions like any other objects, so we can pass them to other functions as parameters (usually,
callbacks in Node.js):
var convertNum = function (num) {
return num + 10;
}
var processNum = function (num, fn) {
return fn(num);
}
processNum(10, convertNum);
Function Invocation vs. Expression
The function definition is as follows:
function f () {};
Chapter 1 ■ Setting up Node.js and Other Essentials
12
On the other hand, the function invocation looks like
f();
Expression, because it resolves to some value (which could be a number, string, object, or boolean), is as follows:
function f() {return false;}
f();
A statement looks like
function f(a) {console.log(a);}
Arrays
Arrays are also objects that have some special methods inherited from the Array.prototype2
global object.
Nevertheless, JavaScript arrays are not real arrays; instead, they are objects with unique integer (usually 0 based) keys.
var arr = [];
var arr2 = [1, Hi, {a:2}, function () {console.log('boo');}];
var arr3 = new Array();
var arr4 = new Array(1,Hi, {a:2}, function () {console.log('boo');});
Prototypal Nature
There are no classes in JavaScript because objects inherit directly from other objects, which is called prototypal
inheritance. There are a few types of inheritance patterns in JavaScript:
Classical
•
Pseudoclassical
•
Functional
•
This is an example of the functional inheritance pattern:
var user = function (ops) {
return { firstName: ops.name || 'John'
, lastName: ops.name || 'Doe'
, email: ops.email || 'test@test.com'
, name: function() { return this.firstName + this.lastName}
}
}
var agency = function(ops) {
ops = ops || {}
var agency = user(ops)
agency.customers = ops.customers || 0
agency.isAgency = true
return agency
}
2
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
Chapter 1 ■ Setting up Node.js and Other Essentials
13
Conventions
It’s important to follow the most common language conventions. Some of them are listed here:
Semicolons
•
camelCase
•
Naming
•
Commas
•
Indentations
•
Whitespace
•
These JavaScript/Node.js conventions (with semicolons being an exception) are stylistic and highly preferential.
They don’t impact the execution; however, it’s strongly suggested that you follow one style consistently, especially if
you are a developer working in teams and/or on open-source projects. Some open-source projects might not accept
pull requests if they contain semicolons (e.g., NPM) or if they don’t use comma-first style (e.g., request).
Semicolons
The use of semicolons is optional, except for two cases:
1. In for loop construction: for (var i=0; i++; in)
2. When a new line starts with parentheses, such as when using an immediately invoked
function expression (IIFE): ;(function(){...}())
camelCase
camelCase is the main naming pattern in JavaScript, except for class names, which are CapitalCamelCase. An example
follows:
var MainView = Backbone.View.extend({...})
var mainView = new MainView()
Naming
_ and $ are perfectly legitimate characters for literals (jQuery and Underscore libraries use them a lot). Private
methods and attributes start with _ (and it does nothing by itself!).
Commas
An example of a comma-first approach is as follows:
var obj = { firstName: John
, lastName: Smith
, email: johnsmith@gmail.com
}
Chapter 1 ■ Setting up Node.js and Other Essentials
14
Indentation
Indentation is usually done using either a tab, or four- or two-space indentation, with supporting camps split almost
religiously between the two options.
Whitespace
Usually, there is a space before and after the =, +, {, and } symbols. There is no space on invocation (e.g., arr.push(1);),
but there’s a space when we define an anonymous function: function () {}.
Node.js Globals and Reserved Keywords
Despite being modeled after one standard, Node.js and browser JavaScript differ when it comes to globals. This was
done intentionally because when var is omitted, browser JavaScript leaks variables infamously to the global space,
thus polluting it. This has been dubbed as one of the bad parts of JavaScript in the canonical book JavaScript: The
Good Parts by Douglas Crockford (2008 O’Reilly).
As you might know, in browser JavaScript we have a window object. However, in Node.js, it is absent (obviously we
don’t deal with a browser window), but developers are provided with new objects/keywords:
• process
• global
• module.exports and exports
So, let’s take a look at the main differences between Node.js and JavaScript.
Node.js Process Information
Each Node.js script that runs is, in essence, a process. For example, ps aux | grep 'node' outputs all Node.js
programs running on a machine. Conveniently, developers can access useful process information in code with the
process object (e.g., node -e console.log(process.pid)), as shown in Figure 1-5.
Chapter 1 ■ Setting up Node.js and Other Essentials
15
Accessing Global Scope in Node.js
As you know, browser JavaScript, by default, puts everything into its global scope. On the other hand, Node.js was
designed to behave differently, with everything being local by default. In case we need to access globals, there is a
global object. And, when we need to export something, we should do so explicitly.
In a sense, the window object from front-end/browser JavaScript metamorphosed into a combination of global
and process objects. Needless to say, the document object, which represents the DOM (Document Object Model) of
the web page, is nonexistent in Node.js.
Exporting and Importing Modules
Another bad part in browser JavaScript is that there is no way to include modules. Scripts are supposed to be
linked together using a different language (HTML), but dependency management is lacking. CommonJS
(http://www.commonjs.org/) and RequireJS (http://requirejs.org/) solve this problem with the AJAX-y
approach. Node.js borrowed many things from the CommonJS concept.
To export an object in Node.js, use exports.name = object;. An example follows:
var messages = {
find: function(req, res, next) {
...
},
add: function(req, res, next) {
...
},
format: 'title | date | author'
}
exports.messages = messages;
Figure 1-5. Node.js process examples using pid (process ID) and cwd (current working directory)
Chapter 1 ■ Setting up Node.js and Other Essentials
16
While in the file where we import the aforementioned script (assuming the path and the file name is
route/messages.js), write the following:
var messages = require('./routes/messages.js');
However, sometimes it’s more fitting to invoke a constructor, such as when we attach properties to the Express.js
app (which is explained in detail in Express.js FUNdamentals: An Essential Overview of Express.js [2013],
http://webapplog.com/express-js-fundamentals/). In this case, module.exports is needed:
module.exports = function(app) {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
return app;
}
In the file that includes the previous sample module, write
...
var app = express();
var config = require('./config/index.js');
app = config(app);
...
The more succinct code is var = express(); require('./config/index.js')(app);.
The most common mistake when including modules is creating a wrong path to the file. For core Node.js
modules, use the name without any path—for example, require('name'). The same goes for modules in the
node_modules folder (more on this when we examine NPM later in the chapter).
For all other files (i.e., not modules), use . with or without a file extension. An example follows:
var keys = require('./keys.js'),
messages = require('./routes/messages.js');
In addition, for including files, it’s possible to use longer statements with __dirname and path.join()—for
example, require(path.join(__dirname, ,'routes', 'messages'));. This is a recommended approach, because
path.join() will produce a path with valid slashes (forward or backward depending on your OS).
If require() points to a folder, Node.js attempts to read the index.js file in that folder.
__dirname vs. process.cwd
__dirname is an absolute path to the file in which the global variable is called, whereas process.cwd is an absolute
path to the process that runs the script. The latter might not be the same as the former if we started the program from
a different folder, such as $ node ./code/program.js.
Chapter 1 ■ Setting up Node.js and Other Essentials
17
Browser Application Programming Interface Helpers
There are myriad helper functions in Node.js from the browser JavaScript application programming interface (API).
The most useful come from String, Array, and Math objects. To make you aware of their existence, or to remind you,
here is a list of the most common functions and their meanings:
• Array
• some() and every(): assertions for array items
• join() and concat(): convertion to a string
• pop(), push(), shift(), and unshift(): working with stacks and queues
• map(): model mapping for array items
• filter(): querying array items
• sort(): ordering items
• reduce(), reduceRight(): computing
• slice(): copying
• splice(): removing
• indexOf(): lookups of finding the value in the array
• reverse(): reversing the order
The
• in operator: iteration over array items
• Math
• random(): random real number less than one
• String
• substr() and substring(): extracting substrings
• length: length of the string
• indexOf(): index of finding the value in the string
• split(): converting the string to an array
In addition, we have setInterval(), setTimeout(), forEach(), and console methods in Node.js. For the
complete list of methods and examples, visit the following sites:
• String (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
Global_Objects/String)
• Array (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
Global_Objects/Array)
• Math (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
Global_Objects/Math)
Chapter 1 ■ Setting up Node.js and Other Essentials
18
Node.js Core Modules
Unlike other programming technologies, Node.js doesn’t come with a heavy standard library. The core modules of
node.js are a bare minimum, and the rest can be cherry-picked via the NPM registry. The main core modules, classes,
methods, and events include the following:
• http (http://nodejs.org/api/http.html#http_http)
• util (http://nodejs.org/api/util.html)
• querystring (http://nodejs.org/api/querystring.html)
• url (http://nodejs.org/api/url.html)
• fs (http://nodejs.org/api/fs.html)
http (http://nodejs.org/api/http.html)
http is the main module responsible for the Node.js HTTP server. The main methods are as follows:
• http.createServer(): returns a new web server object
• http.listen(): begins accepting connections on the specified port and hostname
• http.createClient(): is a client and makes requests to other servers
• http.ServerRequest(): passes incoming requests to request handlers
• data: emitted when a part of the message body is received
• end: emitted exactly once for each request
• request.method(): the request method as a string
• request.url(): request URL string
• http.ServerResponse(): creates this object internally by an HTTP server — not by
the user— and is used as an output of request handlers
• response.writeHead(): sends a response header to the request
• response.write(): sends a response body
• response.end(): sends and ends a response body
util (http://nodejs.org/api/util.html)
The util module provides utilities for debugging. One method is as follows:
• util.inspect(): returns a string representation of an object, which is useful for debugging
querystring (http://nodejs.org/api/querystring.html)
The querystring module provides utilities for dealing with query strings. Some of the methods include the following:
• querystring.stringify(): serializes an object to a query string
• querystring.parse(): deserializes a query string to an object
Chapter 1 ■ Setting up Node.js and Other Essentials
19
url (http://nodejs.org/api/url.html)
The url module has utilities for URL resolution and parsing. One method is as follows:
• parse(): takes a URL string and returns an object
fs (http://nodejs.org/api/fs.html)
fs handles file system operations such as reading to and writing from files. There are synchronous and asynchronous
methods in the library. Some of the methods include the following:
• fs.readFile(): reads files asynchronously
• fs.writeFile(): writes data to files asynchronously
There is no need to install or download core modules. To include them in your application, all you need is to use
the following syntax:
var http = require('http');
A list of noncore modules is found at the following locations:
npmjs.org
• (https://npmjs.org): for the NPM registry
GitHub hosted list
• (https://github.com/joyent/node/wiki/Modules): for Node.js modules
maintained by Joyent
nodetoolbox.com
• (http://nodetoolbox.com/): for a registry based on stats
Nipster
• (http://eirikb.github.com/nipster/): for NPM search tools for Node.js
Node tracking (
• http://nodejsmodules.org): for a registry based on GitHub stats
If you want to know how to code your own modules, take a look at the article “Your First Node.js Module3
.”
Handy Node.js Utilities
Although the core of the Node.js platform was, intentionally, kept small, it has some essential utilities, including
the following:
• Crypto(http://nodejs.org/api/crypto.html): has randomizer, MD5, HMAC-SHA1, and
other algorithms
• Path(http://nodejs.org/api/path.html): handles system paths
• String decoder(http://nodejs.org/api/string_decoder.html): decodes to and from buffer
and string types
The method we use throughout is path.join and it concatenates the path using an appropriate folder
separator (/ or ).
3
http://cnnr.me/blog/2012/05/27/your-first-node-dot-js-module/
Chapter 1 ■ Setting up Node.js and Other Essentials
20
Reading to and Writing from the File System in Node.js
Reading from files is done via the core fs module (http://nodejs.org/api/fs.html). There are two sets of reading
methods: async and sync. In most cases, developers should use async methods, such as fs.readFile:
var fs = require('fs');
var path = require('path');
fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, function (err, data) {
if (err) throw err;
console.log(data);
});
To write to the file, execute the following:
var fs = require('fs');
fs.writeFile('message.txt', 'Hello World!', function (err) {
if (err) throw err;
console.log('Writing is done.');
});
Streaming Data in Node.js
Streaming data is a phrase that means an application processes the data while it’s still receiving it. This feature is
useful for extra large datasets such as video or database migrations.
Here’s a basic example of using streams that output the binary file content back:
var fs = require('fs');
fs.createReadStream('./data/customers.csv').pipe(process.stdout);
By default, Node.js uses buffers for streams. For more immersive instruction, take a look at stream-adventure
(http://npmjs.org/stream-adventure) and Stream Handbook (https://github.com/substack/stream-handbook).
Installing Node.js Modules with NPM
NPM comes with the Node.js platform and allows for seamless Node.js package management. The way npm install
works is similar to Git in the way it traverses the working tree to find a current project (https://npmjs.org/doc/
files/npm-folders.html). For starters, keep in mind that we need either the package.json file or the node_modules
folder to install modules locally with $ npm install name. For example, $ npm install superagent; in the program.
js write: var superagent = require('superagent');.
The best thing about NPM is that it keeps all the dependencies local, so if module A uses module B v1.3, and
module C uses module B v2.0 (with breaking changes compared with v1.3), both A and C will have their own localized
copies of different versions of B. This proves to be a more superior strategy than that of Ruby and other platforms that
use global installations by default.
The best practice is not to include a node_modules folder in the Git repository when the project is a module that
is supposed to be used in other applications. However, it’s recommended to include node_modules for deployable
applications to prevent breakage caused by unfortunate dependency updates.
Note
■
■  The NPM creator likes to call it npm (lowercase, http://npmjs.org/doc/misc/npm-faq.html).
Chapter 1 ■ Setting up Node.js and Other Essentials
21
Taming Callbacks in Node.js
Callbacks (https://github.com/maxogden/art-of-node) are able to make Node.js code asynchronous, yet
programmers unfamiliar with JavaScript, who work with Java or PHP, might be surprised when they see Node.js code
described on Callback Hell (http://callbackhell.com/):
fs.readdir(source, function(err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function(filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function(err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function(width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})
There’s nothing to be afraid of here as long as two-space indentation is used. ;-) However, callback code can be
rewritten with the use of event emitters or promises, or by using the async library.
Hello World Server with HTTP Node.js Module
Although, Node.js can be used for a wide variety of tasks, it’s used primarily for building web applications. Node.js
thrives in the network as a result of its asynchronous nature and built-in modules such as net and http.
Here’s a quintessential Hello World example in which we create a server object, define the request handler
(function with req and res arguments), pass some data back to the recipient, and start up the whole thing (hello.js):
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Let’s break it down a bit (if you know this already, skip to the next section). The following loads the core http
module for the server (more on the modules later):
var http = require('http');
Chapter 1 ■ Setting up Node.js and Other Essentials
22
This snippet below creates a server with a callback function which contains the response handler code:
var server = http.createServer(function (req, res) {
To set the right header and status code, use the following:
res.writeHead(200, {'Content-Type': 'text/plain'});
To output Hello World with the line end symbol, use
res.end('Hello Worldn');
});
The req and res arguments have all the information about a given HTTP request and response correspondingly.
In addition, req and res can be used as streams (see previous section).
To make the server accept requests, use the following:
... listen(1337, '127.0.0.1');
From the folder in which you have server.js, launch in your terminal the following command:
$ node server.js
Open localhost:1337 or 127.0.0.1:1337 or any other address you see in the terminal as a result of the console.log()
function and you should see Hello World in a browser. To shut down the server, press Control + c (on Mac OS X).
Note
■
■  The name of the main file could be different from server.js (e.g., index.js or app.js). In case you need to launch
the app.js file, just use $ node app.js.
Debugging Node.js Programs
Modern-day software developers, especially those who use compiled languages such as Java, get accustomed to rich
tool sets for debugging purposes. Back in the day, before JavaScript and AJAX apps were starting to gain momentum
(~2005–2007), the only way to debug was to put a bunch of alert() statements everywhere. Now, there are amazing
environments such as Chrome Developer Tools and Firefox Firebug! Also, because Node.js has a lot of things in common
with the browser JavaScript environment, we have plenty of options for debugging in Node.js, including the following:
• Core Node.js Debugger: a nongraphic user interface (non-GUI) minimalistic tool that works
everywhere
• Node Inspector: port of Google Chrome Developer Tools
WebStorm and other IDEs (covered in the next section)
•
Core Node.js Debugger
The best debugger is console.log(), because it doesn’t break/interrupt the flow, and it is fast and informative. However,
to use it, we first need to know where to put it. Sometimes, we just don’t know where to put the logs! Other times, we
need to see the call stack and orient ourselves in the async code a bit more. To do this, put debugger statements in your
code and use $ node debug program.js to start the debugging process (http://nodejs.org/api/debugger.html).
Chapter 1 ■ Setting up Node.js and Other Essentials
23
For example, the Hello World from the previous section can be enhanced with debugger in two places: when an
instance is created and when a request is made (hello-debug.js):
var http = require('http');
debugger;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
debugger;
res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Now, if we run the previous snippet (hello-debug.js), just like we did earlier ($ node hello-debug.js), nothing
changes, because we need to use $ node debug hello-debug.js. And only then, the execution halts at the first line,
and then again on the next debugger statement if we use the cont command.
The main node debug commands are as follows:
• next, n: step to the next statement
• cont, c: continue until the next debugger/break point
• step, s: step inside the function call
• out, o: step outside the function call
• watch(expression): watch the expression
The full list of commands is available through the help command or on the official web site
(http://nodejs.org/api/debugger.html).
So, in our example (hello-debug.js), after we start the debugger client and execute cont or c twice (first for
the first line and second for our debugger on the second line), the server will be up and running. After that, we can
open the browser at (http://localhost:1337/) or execute $ curl (http://localhost:1337/) in the Terminal/
Command line, and the debugger client stops inside the request handler (line 5). Now we can use repl and console.
log(req) to inspect the HTTP response object dynamically.
Debugging with Node Inspector
The built-in Node.js debugger client is extensive, but it’s not intuitive because of the lack of a GUI. Therefore, for a
more developer-friendly interface than the core Node.js debugger provides, node-inspector (https://github.com/
node-inspector/node-inspector) comes to the rescue!
To download and install Node Inspector, we use our beloved NPM in the global mode (-g or --global):
$ npm install -g node-inspector
Then, we start Node Inspector with the following (Figure 1-6):
$ node-inspector
Chapter 1 ■ Setting up Node.js and Other Essentials
24
Now start the program in a new terminal window/tab/session with --debug or --debug-brk flags (not just debug;
Figure 1-7). For example:
$ node --debug-brk hello-debug.js
or
$ node --debug hello-debug.js
Figure 1-6. Running the Node Inspector tool
Chapter 1 ■ Setting up Node.js and Other Essentials
25
Open http://127.0.0.1:8080/debug?port=5858 or http://localhost:8080/debug?port=5858 in Chrome
(it must be Chrome and not another browser because Node Inspector uses the Web Developer Tools interface).
You should be able to see the program halted at a break point. Clicking the blue play button resumes the execution,
as shown in Figure 1-8.
Figure 1-7. Running node server in --debug mode
Chapter 1 ■ Setting up Node.js and Other Essentials
26
If we let the server run and open http://localhost:1337/ in a new browser tab, this action pauses the execution
on the second break point, which is inside the request handler. From here, we can use Node Inspector’s right GUI and
add a res watcher (Figure 1-9), which is way better than the terminal window output!
Figure 1-8. Resuming execution in Node Inspector
Chapter 1 ■ Setting up Node.js and Other Essentials
27
In addition, we can follow the call stack, explore scope variables, and execute any Node.js command in the
console tab (Figure 1-10)!
Figure 1-9. Inspecting res object in Node Inspector
Chapter 1 ■ Setting up Node.js and Other Essentials
28
Node.js IDEs and Code Editors
OneofthebestthingsaboutNode.jsisthatyoudon’tneedtocompilethecode,becauseit’sloadedintomemoryand
interpretedbytheplatform!Therefore,alightweighttexteditorishighlyrecommended,suchasSublimeText(Figure1-11),
vs.afull-blownIDE.However,ifyouarealreadyfamiliarandcomfortablewiththeIDEofyourchoice,suchasEclipse
(http://www.eclipse.org/),NetBeans(http://netbeans.org/),orAptana(http://aptana.com/),feelfreetostickwithit.
Figure 1-10. Writing to response (i.e., the res object) from the Node Inspector console
Figure 1-11. Sublime Text code editor home page
Chapter 1 ■ Setting up Node.js and Other Essentials
29
The following is a list of the most popular text editors and IDEs used in web development:
• TextMate (http://macromates.com/): Mac OS X version only, free 30-day trial for v1.5, dubbed
The Missing Editor for Mac OS X
• Sublime Text (http://www.sublimetext.com/): Mac OS X and Windows versions are available,
an even better alternative to TextMate, with an unlimited evaluation period
• Coda (http://panic.com/coda/): an all-in-one editor with an FTP browser and preview, has
support for development with an iPad
• Aptana Studio (http://aptana.com/): a full-size IDE with a built-in terminal and many other tools
• Notepad ++ (http://notepad-plus-plus.org/): a free, Windows-only lightweight text editor
with the support of many languages
• WebStorm IDE (http://www.jetbrains.com/webstorm/): a feature-rich IDE that allows for
Node.js debugging, developed by JetBrains and marketed as “the smartest JavaScript IDE”
(Figure 1-12)
Figure 1-12. WebStorm IDE home page
For most developers, a simple code editor such as Sublime Text 2, TextMate, or Emacs is good enough. However, for
programmers who are used to working in IDEs, there’s WebStorm by JetBrains (http://www.jetbrains.com/webstorm).
For an example of the WebStorm work space, see Figure 1-13.
Chapter 1 ■ Setting up Node.js and Other Essentials
30
Watching for File Changes
If you are familiar with watching for file changes or it’s not an issue for you, feel free to skip this section.
Node.js applications are stored in memory, and if we make changes to the source code, we need to restart the
process (i.e., node). We do this manually by killing the process and starting a new one (Control + c on Macs and Ctrl
+ c on Windows). However, it’s faster for development if this constant sequence of restarts is automated. There are
brilliant tools that leverage the watch method from the core Node.js fs module and restart servers when we save
changes from an editor:
forever (
• http://npmjs.org/forever) (GitHub, http://github.com/nodejitsu/forever)
usually used in production (we examine this topic in Chapter 11)
node-dev(
• https://npmjs.org/package/node-dev)(GitHub, https://github.com/fgnass/node-dev)
Figure 1-13. Webstorm IDE work space
Chapter 1 ■ Setting up Node.js and Other Essentials
31
nodemon (
• https://npmjs.org/package/nodemon) (GitHub, https://github.com/remy/nodemon)
supervisor (
• https://npmjs.org/package/supervisor) (GitHub, https://github.com/
isaacs/node-supervisor)
up (
• https://npmjs.org/package/up) (GitHub, https://github.com/LearnBoost/up), now a
deprecated module
Any one of these tools is as easy to use as installing globally with $ npm install -g node-dev, then running the
Node.js script with $ node-dev program.js. Just replace node-dev with another module name.☺
For a comparison between these tools, refer to Comparison: Tools to Automate Restarting Node.js Server After
Code Changes (http://strongloop.com/strongblog/comparison-tools-to-automate-restarting-node-js-
server-after-code-changes-forever-nodemon-nodesupervisor-nodedev/).
Tip
■
■  It’s good to know that Express.js reloads a template file for every new request by default. So, no server restart
is necessary. However, we can cache templates by enabling the view cache setting. For more Express.js setting, take a
look at Pro Express.js 4 [2014, Apress].
Summary
In this chapter, we explored Installing Node.js and NPM, and launching Node.js scripts from the command line.
We also looked at the essential concepts of Node.js syntax and the platform. Last, lists of Node.js IDEs and libraries
for development were provided.
In the next chapter, we dive deep into using the most popular Node.js framework for creating web apps.
33
Chapter 2
Using Express.js 4 to Create Node.js
Web Apps
It’s only logical that, by using frameworks, software engineers become more productive and can achieve results faster.
Often, the results are of a better quality because the frameworks are used and maintained by many other developers
and contributors. Even if developers build everything from scratch, they end up with their own framework in the end.
It’s just a very customized one!
Node.js is a relatively young platform when it comes to frameworks (unlike Ruby or Java), but there’s already a
leader that has become a de facto standard used in the majority of Node.js projects: Express.js.
Express.js is an amazing framework for Node.js projects, and it’s used in the majority of web apps, which is why
this second chapter is dedicated to getting started with this framework.
In this chapter we cover the following topics, which serve as an introduction to Express.js:
What Express.js is
•
How Express.js works
•
Express.js Installation
•
Express.js scaffolding (command-line tool)
•
The Blog Project overview
•
Express.js 4 Hello World example
•
What Is Express.js?
Express.js is a web framework based on the core Node.js http module and Connect (http://www.senchalabs.org/
connect/) components. The components are called middleware and they are the cornerstones of the framework
philosophy configuration over convention. In other words, Express.js systems are highly configurable, which allows
developers to pick freely whatever libraries they need for a particular project. For these reasons, the Express.js
framework leads to flexibility and high customization in the development of web applications.
If you write serious apps using only core Node.js modules (refer to the following snippet for an example), you most
likely find yourself reinventing the wheel by writing the same code continually for similar tasks, such as the following:
Parsing of HTTP request bodies
•
Parsing of cookies
•
Managing sessions
•
Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
34
Organizing routes with a chain of
• if conditions based on URL paths and HTTP methods of
the requests
Determining proper response headers based on data types
•
To illustrate my point, here is an example of a two-route representational state transfer:
http://en.wikipedia.org/wiki/Representational_state_transfer.
(REST) API server, i.e., we have only two end points and they are also called routes. In this application, we use
only core Node.js modules for server functions. A single “userland”/external native MongoDB driver module is used
for persistence. This example is taken from beginner-friendly Rapid Prototyping with JS (http://rpjs.co/):
Agile JavaScript Development by Azat Mardan [2013]:
var http = require('http');
var util = require('util');
var querystring = require('querystring');
var mongo = require('mongodb');
var host = process.env.MONGOHQ_URL ||
'mongodb://@127.0.0.1:27017';
//MONGOHQ_URL=mongodb://user:pass@server.mongohq.com/db_name
mongo.Db.connect(host, function(error, client) {
if (error) throw error;
var collection = new mongo.Collection(
client,
'test_collection'
);
var app = http.createServer(
function (request, response) {
if (
request.method === 'GET' 
request.url === '/messages/list.json'
) {
collection.find().toArray(function(error, results) {
response.writeHead(
200,
{'Content-Type': 'text/plain'}
);
console.dir(results);
response.end(JSON.stringify(results));
});
};
if (
request.method === POST 
request.url === /messages/create.json
) {
request.on('data', function(data) {
collection.insert(
querystring.parse(data.toString('utf-8')),
{safe: true},
function(error, obj) {
if (error) throw error;
response.end(JSON.stringify(obj));
}
Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
35
);
});
};
});
var port = process.env.PORT || 5000;
app.listen(port);
})
As you can see, developers have to do a lot of manual work themselves, such as interpreting HTTP methods and
URLs into routes, and parsing input and output data.
Express.js solves these and many other problems as abstraction and code organization. The framework
provides a model-view-controller-like (MVC-like) structure for your web apps with a clear separation of concerns
(views, routes, models).
For the models (M in MVC), we need to use Mongoose (http://mongoosejs.com/) or Sequelize
(http://sequelizejs.com/) libraries in addition to Express.js— more on this later in the book in Chapter 7. In this
chapter we’ll cover the basics of Express.js. Built on top this framework, Express.js applications can vary from bare-bones,
back-end-only REST APIs to full-blown, highly scalable, full-stack with jade-browser (https://npmjs.org/package/
jade-browser) and Socket.IO (http://socket.io/), real-time web apps. To give some analogies to developers who
are familiar with Ruby—Express.js is often seen as Sinatra, which has a very different approach to the Ruby on Rails
framework. Express.js and Sinatra promote the configurability while Ruby on Rails convention over configuration.
Although Express.js is the most starred library on NPM (as of May 2014), and the most mature and used Node.
js framework, the playing field is still relatively level with many different frameworks, and new ones are released
every month. Some of them, such as Meteor (http://meteor.com/) and DerbyJS (http://derbyjs.com/), show
an interesting trend in attempts to merge front-end and back-end code bases. For a handpicked list of Node.js
frameworks, refer to the Node Framework (http://nodeframework.com/) resource.
When evaluating a Node.js framework for your project, use these easy steps to guide you:
Build a sample app which is usually provided by the creators of frameworks on GitHub or
•
official web sites. See how the app feels in terms of styles and patterns.
Consider the type of application you’re building: prototype, production app, minimum viable
•
product (MVP), small scale, large scale, and so on.
Consider the libraries already familiar to you and determine whether you can or plan to reuse
•
them, and whether your framework plays nicely with them. Provide out-of-the-box solutions:
template engines, database object-relational mapping (http://en.wikipedia.org/wiki/
Object-relational_mapping) libraries (ORMs) / drivers, cascading style sheets
(http://en.wikipedia.org/wiki/Cascading_Style_Sheets) (CSS) frameworks.
Consider the nature of your application: REST API (with a separate front-end client), a
•
traditional web app, or a traditional web app with REST API end points (such as Blog).
Consider whether you need the support of reactive templates with WebSocket from the
•
get-go. (the Meteor framework, anyone?)
Evaluate the number of stars and follows on NPM and GitHub to judge the popularity of the
•
framework. More popular typically means more blog posts, books, screencasts, tutorials, and
programmers exist; less popular means this is a newer framework, a niche/custom choice, or a
poor choice. With newer frameworks, there is a greater chance that contributing back to them
will be valued, so pick your comfortable spot.
Evaluate NPM, GitHub pages, and a framework’s website for the presence of good API
•
documentation with examples or open issues/bugs. If there are more than a few hundred,
depending on popularity, this may not be a good sign. Also, determine the date of the last
commit on the GitHub repository. Anything older than six months is not a good sign.
Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
36
How Express.js Works
Express.js usually has an entry point—aka, a main file. Most of the time, this is the file that we start with the node
command; or export as a module, in some cases. And in this file, we do the following:
1. Include third-party dependencies as well as our own modules, such as controllers, utilities,
helpers, and models
2. Configure Express.js app settings such as template engine and its file extensions
3. Connect to databases such as MongoDB, Redis, or MySQL (optional)
4. Define middleware such as error handlers, static files folder, cookies, and other parsers
5. Define routes
6. Start the app
7. Export the app as a module (optional)
When the Express.js app is running, it’s listening to requests. Each incoming request is processed according to
a defined chain of middleware and routes, starting from top to bottom. This aspect is important in controlling the
execution flow. For example, routes/middleware that are higher in the file have precedence over the lower definitions.
Because we can have multiple middleware functions processing each HTTP request, some of the functions are in
the middle (hence the name middleware). Here are some examples of middleware purposes:
1. Parse cookie information and put it in req object for following middleware/routes
2. Parse parameters from the URL and put it in req object for following middleware/routes
3. Get the information from the database based on the value of the parameter if the user is
authorized (cookie/session) and put it in req object for following middleware/routes
4. Authorize users/requests, or not.
5. Display the data and end the response
Express.js Installation
The Express.js package comes in two flavors:
1. express-generator: a global NPM package that provides the command-line tool for rapid
app creation (scaffolding)
2. express: a local package module in your Node.js app’s node_modules folder
Express.js Version
Before we proceed with installations, let’s check the Express.js versions. We’ll use an exact version 4.1.2 to avoid
confusion resulting from potential future changes to the Express.js skeleton-generating mechanism and the
module API.
For the Express.js Generator, which is a separate module, we’ll use version 4.0.0, which is compatible with
Express.js 4.x. If you have a version other than 4.0.0 ($ express -V to check), you can uninstall it using $ sudo npm
uninstall -g express-generator. Or $ sudo npm uninstall -g express for Express.js 2.x and 3.x. Before, version
4.x, Express.js Generator was a part of the Express.js module itself. After you’ve uninstalled the older versions, install
the proper version with the next section’s commands.
Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
37
Express.js Generator
To install the Express.js Generator as global package, run $ npm install -g express-generator@4.0.0 from
anywhere on your computer. This downloads and links the $ express terminal command to the proper path, so that
later we can access its command-line interface (CLI) for the creation of new apps.
Note
■
■ For Max OS X and Linux users, if there is an error installing globally, most likely your system requires root/
administrator rights to write to the folder. In this case, $ sudo npm install -g express-generator@4.0.0 might be
needed. Refer to Chapter 1 for more information on changing NPM ownership.
Of course, we can be more vague and tell NPM to install the latest version of express-generator: $ npm install
–g express-generator. But in this case your results might be inconsistent with the book’s examples.
The Figure 2-1 shows us results of running the aforementioned command. Please notice the path in Figure 2-1:
/usr/local/lib/node_modules/express-generator. This is where, on Max OS X / Linux systems, NPM puts global
modules by default. We verify the availability of Express.js CLI by running $ express –V.
Figure 2-1. The result of running NPM with -g and $ express -V
Local Express.js
For the local Express.js 4.1.2 module installation, let’s create a new folder express-cli somewhere on your computer:
$ mkdir express-cli. This will be our project folder for the chapter. Now we can open it with $ cd express-cli.
When we are inside the project folder, we can create package.json manually in a text editor or with the $ npm init
terminal command (Figure 2-2).
Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
38
The following is an example of the package.json file with vanilla $ npm init options:
{
name: express-cli,
version: 0.0.1,
description: ,
main: index.js,
scripts: {
test: echo Error: no test specified  exit 1
},
author: ,
license: BSD
}
Lastly, we install the module using NPM:
$ npm install express@4.1.2 --save
Or, if we want to be less specific, which is not recommended for this example, use:
$ npm install express
Note
■
■  If you attempt to run the aforementioned $ npm install express command without the package.json file
or the node_modules folder, the smart NPM will traverse up the directory tree to the folder that has either of these two
things. This behavior mimics Git’s logic somewhat. For more information on the NPM installation algorithm, please refer to
the official documentation at https://npmjs.org/doc/folders.html.
Figure 2-2. The result of running $ npm init
Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
39
Alternatively, we can update the package.json file by specifying the dependency (express: 4.1.2 or
express: 4.x) and run $ npm install.
The following is the package.json file with an added Express.js v4.1.2 dependency (the latest as of May 2014):
{
name: expressjsguide,
version: 0.0.1,
description: ,
main: index.js,
scripts: {
test: echo Error: no test specified  exit 1
},
dependencies: {
express: 4.1.2
},
author: ,
license: BSD
}
$ npm install
In Figure 2-3, we show the result of install Express.js v4.1.2 locally, into the node_modules folder. Please notice the
path after the express@4.1.2 string in Figure 2-3 is now local and not global, as in the case of express-generator.
Figure 2-3. The result of running $ npm install
If you want to install Express.js to an existing project and save the dependency (smart thing to do!) into the
package.json file, which is already present in that project’s folder, run $ npm install express@4.1.2 --save.
To double-check the installation of Express.js and its dependencies, we can run the $ npm ls command, as
shown in Figure 2-4.
Another Random Scribd Document
with Unrelated Content
hotel spoke of him continually. Lord Markham was now the authority
whom she quoted on all subjects. Even Domenico said “meelord” with a
relish. And as for the Durants, their enthusiasm was boundless. Tasie, not
yet quite recovered from the excitement of Constance’s arrival, lost her self-
control altogether when Markham appeared. It was so good of him to come
to church, she said; such an example for the people at the hotels! And so
nice to lose so little time in coming to call upon papa. Of course, papa, as
the clergyman, would have called upon him as soon as it was known where
he was staying. But it was so pretty of Lord Markham to conform to foreign
ways and make the first visit. “We knew it must be your doing, Frances,”
she said, with grateful delight.
“But, indeed, it was not my doing. It is Constance who makes him
come,” Frances cried.
Constance, indeed, insisted upon his company everywhere. She took him
not only to the Durants, but to the bungalow up among the olive woods,
which they found in great excitement, and where the appearance of Lord
Markham partially failed of its effect, a greater hero and stranger being
there. George Gaunt, the General’s youngest son, the chief subject of his
mother’s talk, the one of her children about whom she always had
something to say, had arrived the day before, and in his presence even a
living lord sank into a secondary place. Mrs Gaunt had been the first to see
the little party coming along by the terraces of the olive woods. She had,
long, long ago, formed plans in her imagination of what might ensue when
George came home. She ran out to meet them with her hands extended. “Oh
Frances, I am so glad to see you! Only fancy what has happened. George
has come!”
“I am so glad,” said Frances, who was the first. She was more used to
the winding of those terraces, and then she had not so much to talk of as
Constance and Markham. Her face lighted up with pleasure. “How happy
you must be!” she said, kissing the old lady affectionately. “Is he well?”
“Oh, wonderfully well; so much better than I could have hoped. George,
George, where are you? Oh, my dear, I am so anxious that you should meet!
I want you to like him,” Mrs Gaunt said.
Almost for the first time there came a sting of pain to Frances’ heart. She
had heard a great deal of George Gaunt. She had thought of him more than
of any other stranger. She had wondered what he would be like, and smiled
to herself at his mother’s too evident anxiety to bring them together, with a
slight, not disagreeable flutter of interest in her own consciousness. And
now here he was, and she was going away! It seemed a sort of spite of
fortune, a tantalising of circumstances; though, to be sure, she did not know
whether she should like him, or if Mrs Gaunt’s hopes might bear any fruit.
Still, it was the only outlet her imagination had ever had, and it had amused
and given her a pleasant fantastic glimpse now and then into something that
might be more exciting than the calm round of every day.
She stood on the little grassy terrace which surrounded the house,
looking towards the open door, but not taking any step towards it, waiting
for the hero to appear. The house was low and broad, with a veranda round
it, planted in the midst of the olive groves, where there was a little clearing,
and looking down upon the sea. Frances paused there, with her face towards
the house, and saw coming out from under the shadow of the veranda, with
a certain awkward celerity, the straight slim figure of the young Indian
officer, his mother’s hero, and, in a visionary sense, her own. She did not
advance—she could not tell why—but waited till he should come up, while
his mother turned round, beckoning to him. This was how it was that
Constance and Markham arrived upon the scene before the introduction was
fully accomplished. Frances held out her hand, and he took it, coming
forward; but already his eyes had travelled over her head to the other pair
arriving, with a look of inquiry and surprise. He let Frances’ hand drop as
soon as he had touched it, and turned towards the other, who was much
more attractive than Frances. Constance, who missed nothing, gave him a
glance, and then turned to his mother. “We brought our brother to see you,”
she said (as Frances had not had presence of mind to do). “Lord Markham,
Mrs Gaunt. But we have come at an inappropriate moment, when you are
occupied.”
“Oh no! It is so kind of you to come. This is my son George, Miss
Waring. He arrived last night. I have so wanted him to meet——” She did
not say Frances; but she looked at the little girl, who was quite eclipsed and
in the background, and then hurriedly added, “your—family: whose name
he knows, as such friends! And how kind of Lord Markham to come all this
way!”
She was not accustomed to lords, and the mother’s mind jumped at once
to the vain, but so usual idea, that this lord, who had himself sought the
acquaintance, might be of use to her son. She brought forward George, who
was a little dazzled too; and it was not till the party had been swept into the
veranda, where the family sat in the evening, that Mrs Gaunt became aware
that Frances had followed, the last of the train, and had seated herself on the
outskirts of the group, no one paying any heed to her. Even then, she was
too much under the influence of the less known visitors to do anything to
put this right.
“I am delighted that you think me kind,” said Markham, in answer to the
assurances which Mrs Gaunt kept repeating, not knowing what to say. “My
step-father is not of that opinion at all. Neither will you be, I fear, when you
know my mission. I have come for Frances.”
“For Frances!” she cried, with a little suppressed scream of dismay.
“Ah, I said you would not be of that opinion long,” Markham said.
“Is Frances going away?” said the old General. “I don’t think we can
stand that. Eh, George? that is not what your mother promised you. Frances
is all we have got to remind us that we were young once. Waring must hear
reason. He must not let her go away.”
“Frances is going; but Constance stays,” interposed that young lady.
“General, I hope you will adopt me in her stead.”
“That I will,” said the old soldier; “that is, I will adopt you in addition,
for we cannot give up Frances. Though, if it is only for a short visit, if you
pledge yourself to bring her back again, I suppose we will have to give our
consent.”
“Not I,” said Mrs Gaunt under her breath. She whispered to her son, “Go
and talk to her. This is not Frances; that is Frances,” leaning over his
shoulder.
George did not mean to shake off her hand; but he made a little impatient
movement, and turned the other way to Constance, to whom he made some
confused remark.
All the conversation was about Frances; but she took no part in it, nor
did any one turn to her to ask her own opinion. She sat on the edge of the
veranda, half hidden by the luxuriant growth of a rose which covered one of
the pillars, and looked out rather wistfully, it must be allowed, over the grey
clouds of olives in the foreground, to the blue of the sea beyond. It was
twilight under the shade of the veranda; but outside, a subdued daylight, on
the turn towards night. The little talk about her was very flattering, but
somehow it did not have the effect it might have had; for though they all
spoke of her as of so much importance, they left her out with one consent.
Not exactly with one consent. Mrs Gaunt, standing up, looking from one to
another, hurt—though causelessly—beyond expression by the careless
movement of her newly returned boy, would have gone to Frances, had she
not been held by some magnetic attraction which emanated from the others
—the lord who might be of use—the young lady, whose careless ease and
self-confidence were dazzling to simple people.
Neither the General nor his wife could realise that she was merely
Frances’ sister, Waring’s daughter. She was the sister of Lord Markham. She
was on another level altogether from the little girl who had been so pleasant
to them all, and so sweet. They were very sorry that Frances was going
away; but the other one required attention, had to be thought of, and put in
the chief place. As for Frances, who knew them all so well, she would not
mind. And thus even Mrs Gaunt directed her attention to the new-comer.
Frances thought it was all very natural, and exactly what she wished. She
was glad, very glad that they should take to Constance; that she should
make friends with all the old friends who to herself had been so tender and
kind. But there was one thing in which she could not help but feel a little
disappointed, disconcerted, cast down. She had looked forward to George.
She had thought of this new element in the quiet village life with a pleasant
flutter of her heart. It had been natural to think of him as falling more or
less to her own share, partly because it would be so in the fitness of things,
she being the youngest of all the society—the girl, as he would be the boy;
and partly because of his mother’s fond talk, which was full of innocent
hints of her hopes. That George should come when she was just going away,
was bad enough; but that they should have met like this, that he should have
touched her hand almost without looking at her, that he should not have had
the most momentary desire to make acquaintance with Frances, whose
name he must have heard so often, that gave her a real pang. To be sure, it
was only a pang of the imagination. She had not fallen in love with his
photograph, which did not represent an Adonis; and it was something, half a
brother, half a comrade, not (consciously) a lover, for which Frances had
looked in him. But yet it gave her a very strange, painful, deserted sensation
when she saw him look over her head at Constance, and felt her hand
dropped as soon as taken. She smiled a little at herself, when she came to
think of it, saying to herself that she knew very well Constance was far
more charming, far more pretty than she, and that it was only natural she
should take the first place. Frances was ever anxious to yield to her the first
place. But she could not help that quiver of involuntary feeling. She was
hurt, though it was all so natural. It was natural, too, that she should be hurt,
and that nobody should take any notice—all the most everyday things in the
world.
George Gaunt came to the Palazzo next day. He came in the afternoon
with his father, to be introduced to Waring; and he came again after dinner
—for these neighbours did not entertain each other at the working-day
meals, so to speak, but only in light ornamental ways, with cups of tea or
black coffee—with both his parents to spend the evening. He was thin and
of a slightly greenish tinge in his brownness, by reason of India and the
illnesses he had gone through; but his slim figure had a look of power; and
he had kind eyes, like his mother’s, under the hollows of his brows: not a
handsome young man, yet not at all common or ordinary, with a soldier’s
neatness and upright bearing. To see Markham beside him with his
insignificant figure, his little round head tufted with sandy hair, his one-
sided look with his glass in his eye, or his ear tilted up on the opposite side,
was as good as a sermon upon race and its advantages. For Markham was
the fifteenth lord; and the Gaunts were, it was understood, of as good as no
family at all. Captain George from that first evening had neither ear nor eye
for any one but Constance. He followed her about shyly wherever she
moved; he stood over her when she sat down. He said little, for he was shy,
poor fellow; yet he did sometimes hazard a remark, which was always
subsidiary or responsive to something she had said.
Mrs Gaunt’s distress at this subversion of all she had intended was great.
She got Frances into a corner of the loggia while the others talked, and
thrust upon her a pretty sandalwood box inlaid with ivory, one of those that
George had brought from India. “It was always intended for you, dear,” she
said. “Of course he could not venture to offer it himself.”
“But, dear Mrs Gaunt,” said Frances, with a low laugh, in which all her
little bitterness evaporated, “I don’t think he has so much as seen my face. I
am sure he would not know me if we met in the road.”
“Oh, my dear child,” cried poor Mrs Gaunt, “it has been such a
disappointment to me. I have just cried my eyes out over it. To think you
should not have taken to each other after all my dreams and hopes.”
Frances laughed again; but she did not say that there had been no failure
of interest on her side. She said, “I hope he will soon be quite strong and
well. You will write and tell me about everybody.”
“Indeed I will. Oh Frances, is it possible that you are going so soon? It
does not seem natural that you should be going, and that your sister should
stay.”
“Not very natural,” said Frances, with a composure which was less
natural still. “But since it is to be, I hope you will see as much of her as you
can, dear Mrs Gaunt, and be as kind to her as you have been to me.”
“Oh, my dear, there is little doubt that I shall see a great deal of her,”
said the mother, with a glance towards the other group, of which Constance
was the central figure. She was lying back in the big wicker-work chair;
with the white hands and arms, which showed out of sleeves shorter than
were usual in Bordighera, very visible in the dusk, accompanying her talk
by lively gestures. The young captain stood like a sentinel a little behind
her. His mother’s glance was half vexation and half pleasure. She thought it
was a great thing for a girl to have secured the attentions of her boy, and a
very sad thing for the girl who had not secured them. Any doubt that
Constance might not be grateful, had not yet entered her thoughts. Frances,
though she was so much less experienced, saw the matter in another light.
“You must remember,” she said, “that she has been brought up very
differently. She has been used to a great deal of admiration, Markham
says.”
“And now you will come in for that, and she must take what she can get
here.” Mrs Gaunt’s tone when she said this showed that she felt, whoever
was the loser, it would not be Constance. Frances shook her head.
“It will be very different with me. And dear Mrs Gaunt, if Constance
should not—do as you wish——”
“My dear, I will not interfere. It never does any good when a mother
interferes,” Mrs Gaunt said hurriedly. Her mind was incapable of pursuing
the idea which Frances so timidly had endeavoured to suggest. And what
could the girl do more?
Next day she went away. Her father, pale and stern, took leave of her in
the bookroom with an air of offence and displeasure which went to Frances’
heart. “I will not come to the station. You will have, no doubt, everybody at
the station. I don’t like greetings in the market-places,” he said.
“Papa,” said Frances, “Mariuccia knows everything. I am sure she will
be careful. She says she will not trouble Constance more than is necessary.
And I hope——”
“Oh, we shall do very well, I don’t doubt.”
“I hope you will forgive me, papa, for all I may have done wrong. I hope
you will not miss me; that is, I hope—oh, I hope you will miss me a little,
for it breaks my heart when you look at me like that.”
“We shall do very well,” said Waring, not looking at her at all, “both you
and I.”
“And you have nothing to say to me, papa?”
“Nothing—except that I hope you will like your new life and find
everything pleasant. Good-bye, my dear; it is time you were going.”
And that was all. Everybody was at the station, it was true, which made
it no place for leave-takings; and Frances did not know that he watched the
train from the loggia till the white plume of steam disappeared with a roar
in the next of those many tunnels that spoil the beautiful Cornice road.
Constance walked back in the midst of the Gaunts and Durants, looking, as
she always did, the mistress of the situation. But neither did Frances, blotted
out in the corner of the carriage, crying behind her veil and her
handkerchief, leaving all she knew behind her, understand with what a tug
at her heart Constance saw the familiar little ugly face of her brother for the
last time at the carriage-window, and turned back to the deadly monotony of
the shelter she had sought for herself, with a sense that everything was over,
and she herself completely deserted, like a wreck upon a desolate shore.
END OF THE FIRST VOLUME.
PRINTED BY WILLIAM BLACKWOOD AND SONS.
A HOUSE
DIVIDED AGAINST ITSELF
BY MRS OLIPHANT
IN THREE VOLUMES
VOL. II.
WILLIAM BLACKWOOD AND SONS
EDINBURGH AND LONDON
MDCCCLXXXVI
A HOUSE DIVIDED AGAINST
ITSELF.
CHAPTER XVII.
“Yes, I hope you will come and see me often. Oh yes, I shall miss my sister;
but then I shall have all the more of papa. Good night. Good night, Captain
Gaunt. No; I don’t sketch; that was Frances. I don’t know the country either.
It was my sister who knew it. I am quite ignorant and useless. Good night.”
Waring, who was on the loggia, heard this in the clear tones of his only
remaining companion. He heard her come in afterwards with a step more
distinct than that of Frances, as her voice carried farther. He said to himself
that everything was more distinct about this girl, and he was glad that she
was coming, glad of some relief from the depression which overcame him
against his will. She came across one room after another, and out upon the
loggia, throwing herself down listlessly in the usurped chair. It did not
occur to him that she was unaware of his presence, and he was surprised
that she said nothing. But after a minute or two, there could be no doubt
why it was that Constance did not speak. There was no loud outburst of
emotion, but a low suppressed sound, which it was impossible to mistake.
She said, after a moment, to herself, “What a fool I am!” But even this
reflection did not stem the tide. A sensation of utter solitude had seized
upon her. She was abandoned, among strangers; and though she had so
much experience of the world, it was not of this world that Constance had
any knowledge. Had she been left alone among a new tribe of people
unknown to her, she would not have been afraid! Court or camp would have
had no alarms for her; but the solitude, broken only by the occasional
appearance of these rustic companions; the simple young soldier, who was
going to bestow his heart upon her, an entirely undesired gift; the anxious
mother, who was about to mount guard over her at a distance; the polite old
beau in the background. Was it possible that the existence she knew had
altogether receded from Constance, and left her with such companions
alone? She was not thinking of her father, neither of himself nor of his
possible presence, which was of little importance to her. After a while she
sat upright and passed her handkerchief quickly over her face. “It is my
own fault,” she said, still to herself; “I might have known.”
“You don’t see, Constance, that I am here.”
She started, and pulled herself up in a moment. “Oh, are you there, papa?
No, I didn’t see you. I didn’t think of any one being here. Well, they are
gone. Everybody came to see Frances off, as you divined. She bore up very
well; but, of course, it was a little sad for her, leaving everything she
knows.”
“You were crying a minute ago, Constance.”
“Was I? Oh, well, that was nothing. Girls cry, and it doesn’t mean much.
You know women well enough to know that.”
“Yes, I know women—enough to say the ordinary things about them,”
said Waring; “but perhaps I don’t know you, which is of far more
consequence just now.”
“There is not much in me to know,” said the girl in a light voice. “I am
just like other girls. I am apt to cry when I see people crying. Frances
sobbed—like a little foolish thing; for why should she cry? She is going to
see the world. Did you ever feel, when you came here first, a sort of horror
seize upon you, as if—as if—as if you were lost in a savage wilderness, and
would never see a human face again?”
“No; I cannot say I ever felt that.”
“No, to be sure,” cried Constance. “What ridiculous nonsense I am
talking! A savage wilderness! with all these houses about, and the hotels on
the beach. I mean—didn’t you feel as if you would like to run violently
down a steep place into the sea?” Then she stopped, and laughed. “It was
the swine that did that.”
“It has never occurred to me to take that means of settling matters; and
yet I understand you,” he said gravely. “You have made a mistake. You
thought you were philosopher enough to give up the world; and it turns out
that you are not. But you need not cry, for it is not too late. You can change
your mind.”
“I—change my mind! Not for the world, papa! Do you think I would
give them the triumph of supposing that I could not do without them, that I
was obliged to go back? Not for the world.”
“I understand the sentiment,” he said. “Still, between these two
conditions of mind, it is rather unfortunate for you, my dear. I do not see
any middle course.”
“Oh yes, there is a middle course. I can make myself very comfortable
here; and that is what I mean to do. Papa, if you had not found it out, I
should not have told you. I hope you are not offended?”
“Oh no, I am not offended,” he said, with a short laugh. “It is perhaps a
pity that everybody has been put to so much trouble for what gives you so
little satisfaction. That is the worst of it; these mistakes affect so many
others besides one’s self.”
Constance evidently had a struggle with herself to accept this reproof;
but she made no immediate reply. After a while: “Frances will be a little
strange at first; but she will like it by-and-by; and it is only right she should
have her share,” she said softly. “I have been wondering,” she went on, with
a laugh that was somewhat forced, “whether mamma will respect her
individuality at all; or if she will put her altogether into my place? I wonder
if—that man I told you of, papa——”
“Well, what of him?” said Waring, rather sharply.
“I wonder if he will be turned over to Frances too? It would be droll.
Mamma is not a person to give up any of her plans, if she can help it; and
you have brought up Frances so very well, papa; she is so docile—and so
obedient——”
“You think she will accept your old lover, or your old wardrobe, or
anything that offers? I don’t think she is so well brought up as that.”
“I did not mean to insult my sister,” cried Constance, springing to her
feet. “She is so well brought up, that she accepted whatever you chose to
say to her, forgetting that she was a woman, that she was a lady.”
Waring’s face grew scarlet in the darkness. “I hope,” he said, “that I am
incapable of forgetting on any provocation that my daughter is a lady.”
“You mean me!” she cried, breathless. “Oh, I can——” But here she
stopped. “Papa,” she resumed, “what good will it do us to quarrel? I don’t
want to quarrel. Instead of setting yourself against me because I am poor
Con, and not Frances, whom you love—— Oh, I think you might be good
to me just at this moment; for I am very lonely, and I don’t know what I am
good for, and I think my heart will break.”
She went to him quickly, and flung herself upon his shoulder, and cried.
Waring was perhaps more embarrassed than touched by this appeal; but
after all, she was his child, and he was sorry for her. He put his arm round
her, and said a few soothing words. “You may be good for a great deal, if
you choose,” he said; “and if you will believe me, my dear, you will find
that by far the most amusing way. You have more capabilities than Frances;
you are much better educated than she is—at least I suppose so, for she was
not educated at all.”
“How do you mean that it will be more amusing? I don’t expect to be
amused; all that is over,” said Constance, in a dolorous tone.
He was so much like her, that he paused for a moment to consider
whether he should be angry, but decided against it, and laughed instead.
“You are not complimentary,” he said. “What I mean is, that if you sit still
and think over your deprivations, you will inevitably be miserable; whereas,
if you exert yourself a little, and make the best of the situation, you will
very likely extract something that is amusing out of it. I have seen it happen
so often in my experience.”
“Ah,” said Constance, considering. And then she withdrew from him and
went back to her chair. “I thought, perhaps, you meant something more
positive. There are perhaps possibilities: Frances would have thought it
wrong to look out for amusement—that must have been because you trained
her so.”
“Not altogether. Frances does not require so much amusement as you do.
It is so in everything. One individual wants more sleep, more food, more
delight than others.”
“Yes, yes,” she cried; “that is like me. Some people are more alive than
others; that is what you mean, papa.”
“I am not sure that it is what I mean; but if you like to take it so, I have
no objection. And in that view, I recommend you to live, Constance. You
will find it a great deal more amusing than to mope; and it will be much
pleasanter to me.”
“Yes,” she said, “I was considering. Perhaps what I mean will be not the
same as what you mean. I will not do it in Frances’ way; but still I will take
your advice, papa. I am sure you are right in what you say.”
“I am glad you think so, my dear. If you cannot have everything you
want, take what you can get. It is the only true philosophy.”
“Then I will be a true philosopher,” she said, with a laugh. The laugh
was more than a mere recovery of spirits. It broke out again after a little, as
if with a sense of something irresistibly comic. “But I must not interfere too
much with Mariuccia, it appears. She knows what you like better than I do.
I am only to look wise when she submits her menu, as if I knew all about it.
I am very good at looking as if I knew all about it. By the way, do you
know there is no piano? I should like to have a piano, if I might.”
“That will not be very difficult,” he said. “Can you play?”
At which she laughed once more, with all her easy confidence restored.
“You shall hear, when you get me a piano. Thanks, papa; you have quite
restored me to myself. I can’t knit you socks, like Frances; and I am not so
clever about the mayonnaises; but still I am not altogether devoid of
intellect. And now, we completely understand each other. Good night.”
“This is sudden,” he said. “Good night, if you think it is time for that
ceremony.”
“It is time for me; I am a little tired; and I have got some alterations to
make in my room, now that—now that—at present when I am quite settled
and see my way.”
He did not understand what she meant, and he did not inquire. It was of
very little consequence. Indeed it was perhaps well that she should go and
leave him to think of everything. It was not a month yet since the day when
he had met that idiot Mannering on the road. To be sure, there was no proof
that the idiot Mannering was the cause of all that had ensued. But at least it
was he who had first disturbed the calm which Waring hoped was to have
been eternal. He sat down to think, almost grateful to Constance for taking
herself away. He thought a little of Frances hurrying along into the
unknown, the first great journey she had ever taken—and such a journey,
away from everything and everybody she knew. Poor little Fan! he thought
a little about her; but he thought a great deal about himself. Would it ever be
possible to return to that peace which had been so profound, which had
ceased to appear capable of disturbance? The circumstances were all very
different now. Frances, who would think it her duty to write to him often,
was henceforth to be her mother’s companion, reflecting, no doubt, the
sentiments of a mind, to escape from the companionship of which he had
given up the world and (almost) his own species. And Constance, though
she had elected to be his companion, would no doubt all the same write to
her mother; and everything that he did and said, and all the circumstances
of his life, would thus be laid open. He felt an impatience beyond words of
that dutifulness of women, that propriety in which girls are trained, which
makes them write letters. Why should they write letters? But it was
impossible to prevent it. His wife would become a sort of distant witness of
everything he did. She would know what he liked for dinner, the wine he
preferred, how many baths he took. To describe how this thought annoyed
him would be impossible. He had forgotten to warn Frances that her father
was not to be discussed with my lady. But what was the use of saying
anything, when letters would come and go continually from the one house
to the other? And he would be compelled to put up with it, though nothing
could be more unpleasant. If these girls had been boys, this would not have
happened. It was perhaps the first time Waring had felt himself within reach
of such a wish, for boys were far more objectionable to his fine taste than
girls, gave more trouble, and were less agreeable to have about one. In the
present circumstances, however, he could not but feel they would have been
less embarrassing. Constance might grow tired, indeed, of that unprofitable
exercise of letter-writing. But Frances, he felt sure, would in all cases be
dutiful, and would not grow tired. She would write to him perhaps (he
shivered) every day; at least every week; and she would think it her duty to
tell him everything that happened, and she would require that he should
reply. But this, except once or twice, perhaps, to let her down easily, he was
resolved that nothing should induce him to do.
Constance was neither tired nor sleepy when she went to her room. She
had never betrayed the consciousness in any way, being high-bred and
courteous when it did not interfere with her comfort to be so; yet she had
divined that Frances had given up her room to her. This would have touched
the heart of many people, but to Constance it was almost an irritation. She
could not think why her sister had done it, except with that intention of self-
martyrdom with which so many good people exasperate their neighbours.
She would have been quite as comfortable in the blue room, and she would
have liked it better. Now that Frances was safely gone and her feelings
could not be hurt any more, Constance had set her heart upon altering it to
her own pleasure, making it bear no longer the impress of Frances’ mind,
but of her own. She took down a number of the pictures which Frances had
thought so much of, and softly pulled the things about, and changed it more
than any one could have supposed a room could be changed. Then she sat
down to think. The depression which had seized upon her when she had felt
that all was over, that the door was closed upon her, and no place of
repentance any longer possible, did not return at first. Her father’s words,
which she understood in a sense not intended by him, gave her a great deal
of amusement as she thought them over. She did not conceal from herself
the fact that there might ensue circumstances in which she should quote
them to him to justify herself. “Frances does not require so much
amusement as you do. One individual requires more sleep, more food, more
delight than another.” She laid this dangerous saying up in her mind with
much glee, laughing to herself under her breath: “If you cannot get what
you want, you must take what you can get.” How astounded he would be if
it should ever be necessary to put him in mind of these dogmas—which
were so true! Her father’s arguments, indeed, which were so well meant,
did not suit the case of Constance. She had been in a better state of mind
when she had felt herself to awake, as it were, on the edge of this desert,
into which, in her impatience, she had flung herself, and saw that there was
no escape for her, that she had been taken at her word, that she was to be
permitted to work out her own will, and that no one would forcibly interfere
to restore all her delights, to smooth the way for her to return. She had
expected this, if not consciously, yet with a strong unexpressed conviction.
But when she had seen Markham’s face disappear, and realised that he was
gone, actually gone, and had left her to exist as she could in the wilderness
to which she had flown, her young perverse soul had been swept as by a
tempest.
After a while, when she had gone through that little interview with her
father, when she had executed her little revolution, and had seated herself in
the quiet of the early night to think again over the whole matter, the pang
returned, as every pang does. It was not yet ten o’clock, the hour at which
she might have been setting out to a succession of entertainments under her
mother’s wing; but she had nothing better to amuse her than to alter the
arrangement of a few old chairs, to draw aside a faded curtain, and then to
betake herself to bed, though it was too early to sleep. There were sounds of
voices still audible without—people singing, gossiping, enjoying, on the
stone benches on the Punto, just those same delights of society which happy
people on the verge of a new season were beginning to enjoy. But
Constance did not feel much sympathy with the villagers, who were
foreigners, whom she felt to be annoying and intrusive, making a noise
under her windows, when, as it so happened, she had nothing to do but to
go to sleep. When she looked out from the window and saw the pale sky
spreading clear over the sea, she could think of nothing but Frances rushing
along through the night, with Markham taking such care of her, hastening to
London, to all that was worth living for. No doubt that little thing was still
crying in her corner, in her folly and ignorance regretting her village. Oh, if
they could but have changed places! To think of sitting opposite to
Markham, with the soft night air blowing in her face, devouring the way,
seeing the little towns flash past, the morning dawn upon France, the long
levels of the flat country sweep along, then Paris, London, at last! She shut
the persiani almost violently with a hand that trembled, and looked round
the four walls which shut her in, with again an impulse almost of despair.
She felt like a wild creature newly caged, shut in there, to be kept within
bolts and bars, to pace up and down, and beat against the walls of her
prison, and never more to go free.
But this fit being more violent, did not go so deep as the unspeakable
sense of loneliness which had overwhelmed her soul at first. She sprang up
from it with the buoyancy of her age, and said to herself what her father had
said: “If you cannot get what you want, you must take what you can get.”
There was yet a little amusement to be had out of this arid place. She had
her father’s sanction for making use of her opportunities; anything was
better than to mope; and for her it was a necessity to live. She laughed a
little under her breath once more, as she came back to this more reassuring
thought, and so lay down in her sister’s bed with a satisfaction in the
thought that it had not taken her any trouble to supplant Frances, and a
mischievous smile about the corners of her mouth; although, after all, the
thought of the travellers came over her again as she closed her eyes, and she
ended by crying herself to sleep.
CHAPTER XVIII.
Captain Gaunt called next day to bring, he said, a message from his
mother. She sent Mr Waring a newspaper which she thought he might like
to see, an English weekly newspaper, which some of her correspondents
had sent her, in which there was an article—— He did not give a very clear
account of this, nor make it distinctly apparent why Waring should be
specially interested; and as a matter of fact, the newspaper found its way to
the waste-paper basket, and interested nobody. But, no doubt, Mrs Gaunt’s
intentions had been excellent. When the young soldier arrived, there was a
carriage at the door, and Constance had her hat on. “We are going,” she
said, “to San Remo, to see about a piano. Do you know San Remo? Oh, I
forgot you are as much a stranger as I am; you don’t know anything. What a
good thing that there are two ignorant persons! We will keep each other in
countenance, and they will be compelled to make all kinds of expeditions to
show us everything.”
“That will be a wonderful chance for me,” said the young man, “for
nobody would take so much trouble for me alone.”
“How can you tell that? Miss Tasie, I should think, would be an
excellent cicerone,” said Constance. She said it with a light laugh of
suggestion, meaning to imply, though, of course, she had said nothing, that
Tasie would be too happy to put herself at Captain Gaunt’s disposition; a
suggestion which he, too, received with a laugh—for this is one of the
points upon which both boys and girls are always ungenerous.
“And failing Miss Tasie,” said Constance, “suppose you come with papa
and me? They say it is a pretty drive. They say, of course, that everything
here is lovely, and that the Riviera is paradise. Do you find it so?”
“I can fancy circumstances in which I should find it so,” said the young
soldier.
“Ah, yes; every one can do that. I can fancy circumstances in which
Bond Street would be paradise—oh, very easily! It is not far from paradise
at any time.”
“That is a heaven of which I know very little, Miss Waring.”
“Ah, then, you must learn. The true Elysian fields are in London in May.
If you don’t know that, you can form no idea of happiness. An exile from
all delights gives you the information, and you may be sure it is true.”
“Why, then, Miss Waring, if you think so——”
“Am I here? Oh, that is easily explained. I have a sister.”
“Yes, I know.”
“Ah, I understand you have heard a great deal about my sister. I suffer
here from being compared with her. I am not nearly so good, so wise, as
Frances. But is that my fault, Captain Gaunt? You are impartial; you are a
new-comer. If I could, I would, be as nice as Frances, don’t you believe?”
The young man gave Constance a look, which, indeed, she expected, and
said with confusion, “I don’t see—any need for improvement,” and blushed
as near crimson as was possible over the greenish brown of his Indian
colour.
Constance for her part did not blush. She laughed, and made him an
almost imperceptible curtsey. The ways of flirtation are not original, and all
the parallels of the early encounters might be stereotyped, as everybody
knows.
“You are very amiable,” she said; “but then you don’t know Frances, and
your opinion, accordingly, is less valuable. I did not ask you, however, to
believe me to be equal to my sister, but only to believe that I would be as
nice if I could. However, all that is no explanation. We have a mother, you
know, in England. We are, unfortunately, that sad thing, a household
divided against itself.”
Captain Gaunt was not prepared for such confidences. He grew still a
little browner with embarrassment, and muttered something about being
very sorry, not knowing what to say.
“Oh, there is not very much to be sorry about. Papa enjoys himself in his
way here, and mamma is very happy at home. The only thing is that we
must each have our turn, you know—that is only fair. So Frances has gone
to mamma, and here am I in Bordighera. We are each dreadfully out of our
element. Her friends condemn me, to begin with, as if it were my fault that I
am not like her; and my friends, perhaps—— But no; I don’t think so.
Frances is so good, so nice, so everything a girl ought to be.”
At this she laughed softly again; and young Gaunt’s consciousness that
his mother’s much vaunted Frances was the sort of girl to please old ladies
rather than young men, a prim, little, smooth, correct maiden, with not the
least “go” in her, took additional force and certainty. Whereas—— But he
had no words in which to express his sense of the advantages on the other
side.
“You must find it,” he said, knowing nothing more original to say,
“dreadfully dull living here.”
“I have not found anything as yet; I have only just come. I am no more
than a few days older than you are. We can compare notes as time goes on.
But perhaps you don’t mean to stay very long in these abodes of the blest?”
“I don’t know that I did intend it. But I shall stay now as long as ever I
can,” said the young man. Then—for he was shy—he added hastily, “It is a
long time since I have seen my people, and they like to have me.”
“Naturally. But you need not have spoiled what looked like a very pretty
compliment by adding that. Perhaps you didn’t mean it for a compliment?
Oh, I don’t mind at all. It is much more original, if you didn’t mean it.
Compliments are such common coin. But I don’t pretend to despise them,
as some girls do; and I don’t like to see them spoiled,” Constance said
seriously.
The young man looked at her with consternation. After a while, his
moustache expanded into a laugh, but it was a confused laugh, and he did
not understand. Still less did he know how to reply. Constance had been
used to sharper wits, who took her at half a word; and she was half angry to
be thus obliged to explain.
“We are going to San Remo, as I told you,” she said. “I am waiting for
my father. We are going to look for a piano. Frances is not musical, so there
is no piano in the house. You must come too, and give your advice. Oh, are
you ready, papa? Captain Gaunt, who does not know San Remo, and who
does know music, is coming with us to give us his advice.”
The young soldier stammered forth that to go to San Remo was the thing
he most desired in the world. “But I don’t think my advice will be good for
much,” he said, conscientiously. “I do a little on the violin; but as for
pretending to be a judge of a piano——”
“Come; we are all ready,” said Constance, leading the way.
Waring had to let the young fellow precede him, to see him get into the
carriage without any articulate murmur. As a matter of fact, a sort of stupor
seized the father, altogether unaccustomed to be the victim of accidents.
Frances might have lived by his side till she was fifty before she would
have thought of inviting a stranger to be of their party—a stranger, a young
man, which was a class of being with which Waring had little patience, a
young soldier, proverbially frivolous, and occupied with foolish matters.
Young Gaunt respectfully left to his senior the place beside Constance; but
he placed himself opposite to her, and kept his eyes upon her with a devout
attention, which Waring would have thought ridiculous had he not been
irritated by it. The young fellow was a great deal too much absorbed to
contribute much to the amusement of the party; and it irritated Waring
beyond measure to see his eyes gleam from under his eyebrows, opening
wider with delight, half closing with laughter, the ends of his moustache
going up to his ears. Waring, an impartial spectator, was not so much
impressed by his daughter’s wit. He thought he had heard a great deal of the
same before, or even better, surely better, for he could recollect that he had
in his day been charmed by a similar treatment, which must have been
much lighter in touch, much less commonplace in subject, because—he was
charmed. Thus we argue in our generations. In the meantime, young Gaunt,
though he had not been without some experience, looked at Constance from
under his brows, and listened as if to the utterances of the gods. If only they
could have had it all to themselves; if only the old father had been out of the
way!
The sunshine, the sea, the beautiful colour, the unexpected vision round
every corner of another and another picturesque cluster of towns and roofs;
all that charm and variety which give to Italy above every country on earth
the admixture of human interest, the endless chain of association which
adds a grace to natural beauty, made very little impression upon this young
pair. She would have been amused and delighted by the exercise of her own
power, and he would have been enthralled by her beauty, and what he
considered her wit and high spirits, had their progress been along the dullest
streets. It was only Waring’s eyes, disgusted by the prospect before him of
his daughter’s little artifices, and young Gaunt’s imbecile subjection, which
turned with any special consciousness to the varying blues of the sea, to the
endless developments of the landscape. Flirtation is one of the last things in
the world to brook a spectator. Its little absurdities, which are so delightful
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

PDF
Practical Nodejs Building Realworld Scalable Web Apps 1st Edition Azat Mardan...
PDF
Node.js Web Development .pdf
PDF
All You Need to Know About Using Node.pdf
PPTX
Node js installation steps.pptx slide share ppts
PDF
Node.js Development Tools
PPTX
module for backend full stack applications 1.pptx
PPTX
02 Node introduction
PDF
Node.js.pdf
Practical Nodejs Building Realworld Scalable Web Apps 1st Edition Azat Mardan...
Node.js Web Development .pdf
All You Need to Know About Using Node.pdf
Node js installation steps.pptx slide share ppts
Node.js Development Tools
module for backend full stack applications 1.pptx
02 Node introduction
Node.js.pdf

Similar to Practical Node js Building Real World Scalable Web Apps 1st Edition Azat Mardan (Auth.) (20)

PPTX
Nodejs
PPTX
Node js Introduction
PDF
Node.js and the MEAN Stack Building Full-Stack Web Applications.pdf
PDF
Node Js Non-blocking or asynchronous Blocking or synchronous.pdf
PPTX
8 Node.js Frameworks Every Developer Should Know [UPDATED].pptx
PPT
Node js
PDF
Create Restful Web Application With Node.js Express Framework
PPTX
Node.js and Enterprise Web Apps: Know all About it
PDF
Why Learn Node.js? Top Benefits for Your Web Development Career
PDF
Nodejs presentation
PDF
React Js vs Node Js_ Which Framework to Choose for Your Next Web Application
PPTX
Basic Concept of Node.js & NPM
PDF
Node.js Web Development.pdf
PDF
Node JS Roadmap for Beginners By Scholarhat PDF
PDF
Node.js and .NET Core.pdf
PDF
Node JS Express: Steps to Create Restful Web App
PPT
Js frameworks
PPTX
Introduction to node.js by jiban
Nodejs
Node js Introduction
Node.js and the MEAN Stack Building Full-Stack Web Applications.pdf
Node Js Non-blocking or asynchronous Blocking or synchronous.pdf
8 Node.js Frameworks Every Developer Should Know [UPDATED].pptx
Node js
Create Restful Web Application With Node.js Express Framework
Node.js and Enterprise Web Apps: Know all About it
Why Learn Node.js? Top Benefits for Your Web Development Career
Nodejs presentation
React Js vs Node Js_ Which Framework to Choose for Your Next Web Application
Basic Concept of Node.js & NPM
Node.js Web Development.pdf
Node JS Roadmap for Beginners By Scholarhat PDF
Node.js and .NET Core.pdf
Node JS Express: Steps to Create Restful Web App
Js frameworks
Introduction to node.js by jiban
Ad

Recently uploaded (20)

PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Lesson notes of climatology university.
PPTX
Cell Structure & Organelles in detailed.
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Computing-Curriculum for Schools in Ghana
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Cell Types and Its function , kingdom of life
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Lesson notes of climatology university.
Cell Structure & Organelles in detailed.
Microbial diseases, their pathogenesis and prophylaxis
Computing-Curriculum for Schools in Ghana
STATICS OF THE RIGID BODIES Hibbelers.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
A systematic review of self-coping strategies used by university students to ...
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Cell Types and Its function , kingdom of life
Final Presentation General Medicine 03-08-2024.pptx
Final Presentation General Medicine 03-08-2024.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
O7-L3 Supply Chain Operations - ICLT Program
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Microbial disease of the cardiovascular and lymphatic systems
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Ad

Practical Node js Building Real World Scalable Web Apps 1st Edition Azat Mardan (Auth.)

  • 1. Practical Node js Building Real World Scalable Web Apps 1st Edition Azat Mardan (Auth.) download https://ebookgate.com/product/practical-node-js-building-real- world-scalable-web-apps-1st-edition-azat-mardan-auth/ Get Instant Ebook Downloads – Browse at https://ebookgate.com
  • 2. Get Your Digital Files Instantly: PDF, ePub, MOBI and More Quick Digital Downloads: PDF, ePub, MOBI and Other Formats Professional Node js Building Javascript Based Scalable Software 1st Edition Pedro Teixeira https://ebookgate.com/product/professional-node-js-building- javascript-based-scalable-software-1st-edition-pedro-teixeira/ Building Serverless Web Applications Develop scalable web apps using the Serverless Framework on AWS 1st Edition Diego Zanon https://ebookgate.com/product/building-serverless-web- applications-develop-scalable-web-apps-using-the-serverless- framework-on-aws-1st-edition-diego-zanon/ Node js Recipes 1st Edition Cory Gackenheimer (Auth.) https://ebookgate.com/product/node-js-recipes-1st-edition-cory- gackenheimer-auth/ Building Scalable Web Sites Building Scaling and Optimizing the Next Generation of Web Applications 1st Edition Cal Henderson https://ebookgate.com/product/building-scalable-web-sites- building-scaling-and-optimizing-the-next-generation-of-web- applications-1st-edition-cal-henderson/
  • 3. Programming JavaScript Applications Robust Web Architecture with Node HTML5 and Modern JS Libraries 1st Edition Eric Elliott https://ebookgate.com/product/programming-javascript- applications-robust-web-architecture-with-node-html5-and-modern- js-libraries-1st-edition-eric-elliott/ Beginning Node js 1st Edition Basarat Ali Syed (Auth.) https://ebookgate.com/product/beginning-node-js-1st-edition- basarat-ali-syed-auth/ Smashing Node js JavaScript everywhere 2nd Edition Guillermo Rauch https://ebookgate.com/product/smashing-node-js-javascript- everywhere-2nd-edition-guillermo-rauch/ Head First HTML5 Programming Building Web Apps with JavaScript 1st Edition Eric T Freeman https://ebookgate.com/product/head-first-html5-programming- building-web-apps-with-javascript-1st-edition-eric-t-freeman/ Node Web Development Second Edition David Herron https://ebookgate.com/product/node-web-development-second- edition-david-herron/
  • 5. For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.
  • 6. v Contents at a Glance About the Author����������������������������������������������������������������������������������������������������������������xv About the Technical Reviewer������������������������������������������������������������������������������������������xvii Acknowledgments�������������������������������������������������������������������������������������������������������������xix Introduction�����������������������������������������������������������������������������������������������������������������������xxi Chapter 1: Setting up Node.js and Other Essentials ■ ■ ����������������������������������������������������������1 Chapter 2: Using Express.js 4 to Create Node.js Web Apps ■ ■ ���������������������������������������������33 Chapter 3: TDD and BDD for Node.js with Mocha ■ ■ ������������������������������������������������������������57 Chapter 4: Template Engines: Jade and Handlebars ■ ■ �������������������������������������������������������71 Chapter 5: Persistence with MongoDB and Mongoskin ■ ■ �������������������������������������������������103 Chapter 6: Using Sessions and OAuth to Authorize and Authenticate ■ ■ Users in Node.js Apps ����������������������������������������������������������������������������������������������������129 Chapter 7: Boosting Your Node.js Data with the Mongoose ORM Library ■ ■ ���������������������149 Chapter 8: Building Node.js REST API Servers with Express.js and Hapi ■ ■ ����������������������173 Chapter 9: Real-Time Apps with WebSocket, Socket.IO, and DerbyJS ■ ■ ��������������������������195 Chapter 10: Getting Node.js Apps Production Ready ■ ■ ����������������������������������������������������215 Chapter 11: Deploying Node.js Apps ■ ■ �����������������������������������������������������������������������������243 Chapter 12: Publishing Node.js Modules and Contributing to Open Source ■ ■ ������������������261 Index���������������������������������������������������������������������������������������������������������������������������������269
  • 7. xxi Introduction There are more and more books and online resources being published that cover Node.js basics (e.g., how-to’s of Hello World and simple apps). For the most part, these tutorials rely on core modules only or maybe one or two Node Package Manager (NPM) packages. This “sandbox” approach of tutorials is easy and doesn’t require many dependencies, but it can’t be further from the actual Node.js stack. This is especially true with Node.js, the core of which—by design—is kept lean and minimal. At the same time, the vast “userland” (i.e., NPM) provides an ecosystem of packages/modules to serve specific granular purposes. Therefore, there is a need to show effectively how Node.js is used in the industry and to have it all in one place—the all-encompassing practical resource that can be used as a learning tool, a code cookbook, and a reference. What This Book Is Practical Node.js: Building Real-World Scalable Web Apps is a hands-on manual for developing production-ready web applications and services by leveraging the rich ecosystem of Node.js packages. This is important because real applications require many components, such as security, deployment, code organization, database drivers, template engines, and more. This is why we include extensive 12-chapter coverage of third-party services, command-line tools, NPM modules, frameworks, and libraries. Just to give you some idea, Practical Node.js is a one-stop place for getting started with Express.js 4, Hapi.js, DerbyJS, Mongoskin, Mongoose, Everyauth, Mocha, Jade, Socket.IO, TravisCI, Heroku, Amazon Web Services (AWS), and many others. Most of these items are vital for any serious project. In addition, we create a few projects by building, step by step, from a straightforward concept to a more complicated application. These projects can also serve as a boilerplate for jump-starting your own development efforts. Also, the examples show industry best practices to help you avoid costly mistakes. Last but not least, many topics and chapters serve as a reference to which you can always return later when you’re faced with a challenging problem. Practical Node.js aims to save you time and make you a more productive Node.js programmer! What You’ll Learn Practical Node.js takes you from an overview of JavaScript and Node.js basics, installing all the necessary modules to writing and deploying web applications, and everything in between. We cover libraries including, but not limited to, Express.js 4 and Hapi.js frameworks, Mongoskin and the Mongoose object-relational mapping (ORM) library for the MongoDB database, Jade and Handlebars template engines, OAuth and Everyauth libraries for OAuth integrations, the Mocha testing framework and Expect test-driven development/behavior-driven development language, and the Socket.IO and DerbyJS libraries for WebSocket real-time communication.
  • 8. ■ Introduction xxii In the deployment chapters (10 and 11), the book covers how to use Git and deploy to Heroku, as well as examples of how to deploy to AWS, daemonize apps, and use Nginx, Varnish Cache, Upstart, init.d, and the forever module. The hands-on approach of this book walks you through iterating on the Blog project in addition to many other smaller examples. You’ll build database scripts, representational state transfer (RESTful) application programming interfaces (APIs), tests, and full-stack apps all from scratch. You’ll also discover how to write your own Node.js modules and publish them on NPM. Practical Node.js will show you how to do the following: Build web apps with Express.js 4, MongoDB, and the Jade template engine • Use various features of Jade and Handlebars • Manipulate data from the MongoDB console • Use the Mongoskin and Mongoose ORM libraries for MongoDB • Build REST API servers with Express.js 4 and Hapi.js • Test Node.js web services with Mocha, Expect, and TravisCI • Use token and session-based authentication • Implement a third-party (Twitter) OAuth strategy with Everyauth • Build WebSocket apps using Socket.IO and DerbyJS libraries • Prepare code for production with Redis, Node.js domains, and the cluster library using tips • and best practices Deploy apps to Heroku using Git • Install necessary Node.js components on an AWS instance • Configure Nginx, Upstart, Varnish, and other tools on an AWS instance • Write your own Node.js module and publish it on NPM • You already know what Node.js is; now, learn what you can do with it and how far you can take it. What This Book Is Not Although the entire first chapter is dedicated to installations and a few important differences between Node.js and browser JavaScript, we didn’t want to dilute the core message of making production-ready apps, or make Practical Node.js even larger and more convoluted. Therefore, the book is not a beginner’s guide and there is no extensive immersion into the inner workings of the Node.js platform and its core modules. We also can’t guarantee that each component and topic are explained to the extent you need, because the nature of your project might be very specific. Most chapters in the book help you to get started with the stack. There is simply no realistic way to fit so many topics in one book and cover them comprehensively. Another caveat of this book (or virtually any other programming book) is that the versions of the packages we use will eventually become obsolete. Often, this isn’t an issue because, in this book, versions are stated and locked explicitly. So no matter what, the examples will continue to work with our versions. Even if you decide to use the latest versions, in many cases this still might not be an issue, because essentials remain the same. However, if you go this off-path route, once in a while you might be faced with a breaking change introduced by the latest versions.
  • 9. ■ Introduction xxiii Who Can Benefit from This Book Practical Node.js is an intermediate- to advanced-level book on programming with Node.js. Consequently, to get the most out of it, you need to have prior programming experience and some exposure to Node.js. We assume readers’ prior knowledge of computer science, programming concepts, web development, Node.js core modules, and the inner workings of HTTP and the Internet. However, depending on your programming level and ability to learn, you can fill in any knowledge gaps very quickly by visiting links to official online documentations and reading external resources referenced in this book. Also, if you have a strong programming background in some other programming language, it would be relatively easy for you to start Node.js development with Practical Node.js. As mentioned earlier, Practical Node.js is written for intermediate and advanced software engineers. For this reason, there are three categories of programmers who can benefit from it the most: 1. Generalist or full-stack developers including development operation (DevOps) and quality assurance (QA) automation engineers 2. Experienced front-end web developers with a strong background and understanding of browser JavaScript 3. Skilled back-end software engineers coming from other languages such as Java, PHP, and Ruby, who don’t mind doing some extra work get up to speed with the JavaScript language Source Code Learning is more effective when we apply our knowledge right away. For this reason, virtually every chapter in Practical Node.js ends with a hands-on exercise. For your convenience, and because we believe in open source and transparency, all the book’s examples are available publicly (i.e., free of charge) for exploration and execution on GitHub at https://github.com/azat-co/practicalnode. Errata and Contacts If you spot any mistakes or typos (and I’m sure you will), please open an issue or, even better, fix it and make a pull request to the GitHub repository of the book’s examples at https://github.com/azat-co/practicalnode. For all other updates and contact information, the canonical home of Practical Node.js on the Internet is http://practicalnodebook.com. Notation This book follows a few formatting conventions. Code is in monospace font—for example, var book = {name: 'Practical Node.js'}; . If the code begins with $, this code is meant to be executed in the terminal/command line. However, if the code line starts with , the code is meant for the virtual environment (a.k.a., console—either for Node.js or MongoDB). If the Node.js module name is in code font, this is the NPM name and you can use it with NPM and the require() method, such as superagent.
  • 10. ■ Introduction xxiv Why You Should Read This Book Practical Node.js was designed to be one stop for going from Hello World examples to building apps in a professional manner. You get a taste of the most widely used Node.js libraries in one place, along with best practices and recommendations based on years of building and running Node.js apps in production. The libraries covered in Practical Node.js greatly enhance the quality of code and make you more productive. Also, although the material in this book is not groundbreaking, the convenience of the format saves hours of frustration researching the Internet. Therefore, Practical Node.js is here to help you to jump-start your Node.js development!.
  • 11. 1 Chapter 1 Setting up Node.js and Other Essentials As with many technologies, it’s vital to have the proper foundation set up first, before moving on to solving more complex problems. In this chapter, we cover the following: Node.js and (NPM) Node Package Manager installation • Node.js script launches • Node.js syntax and basics • Node.js integrated development environments (IDEs) and code editors • Awareness of file changes • Node.js program debugging • Installing Node.js and NPM Although your operating system (OS) might have Node.js installed on it already, you should update to at least 0.10.x. In the following subsection, we examine a few different approaches to installing Node.js: • One-click installers: probably the easiest and fastest way to get started with the platform • Installing with HomeBrew or MacPorts: straightforward installation for Max OS X users • Installing from a tar file: an alternative installation from an archive file • Installing without sudo: the best way to avoid needing sudo (admin rights) when using the node and npm commands • Installing from a Git repo: an option for advanced developers who need the latest version and/or contribute to the project • Multiversion setup with Nave: a must-have for developers contributing to projects that use different Node.js versions • Multiversion setup with Node Version Manager (NVM): alternative to Nave (see previous entry)
  • 12. Chapter 1 ■ Setting up Node.js and Other Essentials 2 One-Click Installers First, let’s go to http://nodejs.org and download a one-click installer for your OS (Figure 1-1) by clicking on the Install button. Don’t choose binaries or source code unless you know what to do with them or your OS is not present there (i.e., not Windows or Mac). Figure 1-1. One-click installers for Node.js The installers come with NPM (Node Package Manager)— an important tool for managing dependencies. If there’s no installer for your OS (page http://nodejs.org/download/), you can get the source code and compile it yourself (Figure 1-2).
  • 13. Chapter 1 ■ Setting up Node.js and Other Essentials 3 Note ■ ■ For older Mac OS X machines, you can pick 32-bit versions. Installing with HomeBrew or MacPorts If you already have HomeBrew (brew) installed, run the following in a straightforward manner: $ brew install node $ brew install npm Similarly, for MacPorts, run $ sudo port install nodejs Figure 1-2. Multiple options for downloading
  • 14. Chapter 1 ■ Setting up Node.js and Other Essentials 4 If your Mac OS X does not have HomeBrew, go to http://brew.sh/ or install it with the following command: $ ruby -e $(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install) Installing from a Tar File To install from a tar file (which is type of archive), set up a folder for the latest Node.js as follows: $ echo 'export PATH=$HOME/local/bin:$PATH' ~/.bashrc $ . ~/.bashrc $ mkdir ~/local $ mkdir ~/node-latest-install $ cd ~/node-latest-install Note ■ ■  Advanced users who choose to make their own Node.js builds need to have certain compilers installed first. For more information, refer to the official documentation (https://github.com/joyent/node/wiki/Installation). Download the tar file with CURL and unpack it: $ curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1 $ ./configure --prefix=~/local Build Node.js and install it: $ make install $ curl https://npmjs.org/install.sh | sh Tip ■ ■  If you find yourself getting errors when trying to install the module globally via NPM ($ npm install -g packagename), reinstall Node.js and NPM with the “Installing Without sudo” solution below to eliminate the need to use sudo with the installation command. For more solutions for advanced users, there’s a Gist from Isaac Z. Schlueter: https://gist.github.com/isaacs/579814. Installing Without sudo Sometimes, depending on your configuration, NPM asks users for sudo— root user permissions. To avoid using sudo, advanced developers can use the following:: $ sudo mkdir -p /usr/local/{share/man,bin,lib/node,include/node} $ sudo chown -R $USER /usr/local/{share/man,bin,lib/node,include/node} Note ■ ■  Please be sure you are comfortable with the functionality of the chown command before you run it.
  • 15. Chapter 1 ■ Setting up Node.js and Other Essentials 5 Then, proceed with a normal installation: $ mkdir node-install $ curl http://nodejs.org/dist/node-v0.4.3.tar.gz | tar -xzf - -C node-install $ cd node-install/* $ ./configure $ make install $ curl https://npmjs.org/install.sh | sh Installing from a Git Repo If you want to use the latest core Node.js code, and maybe even contribute to the Node.js and NPM projects, it’s possible to build the installation from the cloned Git repo. (This step requires Git. To install it, go to http://git-scm.com/ and click Download.) For basic Git commands, refer to Chapter 11, where we explore deployment; otherwise, do the following: 1. Make the folders and add the path: $ mkdir ~/local $ echo 'export PATH=$HOME/local/bin:$PATH' ~/.bashrc $ . ~/.bashrc To clone the original Node.js repo from Joyent (alternatively, you can fork it and clone your own repository), do the following: $ git clone git://github.com/joyent/node.git $ cd node $ ./configure --prefix=~/local 2. Make the build: $ make install $ cd .. 3. Repeat for NPM: $ git clone git://github.com/isaacs/npm.git $ cd npm $ make install For a more cutting-edge NPM version, use $ make link Multiversion Setup with Nave If you plan to run multiple versions of Node.js, use Nave (https://github.com/isaacs/nave), which is a virtual environment for Node.js. First, make a folder: mkdir ~/.nave cd ~/.nave
  • 16. Chapter 1 ■ Setting up Node.js and Other Essentials 6 Then, download Nave and set the link to the PATH-ed folder: $ wget http://github.com/isaacs/nave/raw/master/nave.sh $ sudo ln -s $PWD/nave.sh /usr/local/bin/nave An example of switching to Node.js version 0.4.8 with Nave in a virtual environment is as follows: $ nave use 0.4.8 To use NPM in this particular virtual environment, use $ curl https://npmjs.org/install.sh | sh It is now possible to install something via NPM: $ npm install express Last, exit the virtual environment with exit More approaches to install Node.js and NPM are in gist (https://gist.github.com/isaacs/579814). Multiversion Setup with NVM Another option to Nave is NVM—Node Version Manager (GitHub, https://github.com/creationix/nvm). Install NVM as follows: $ curl https://raw.github.com/creationix/nvm/master/install.sh | sh or $ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh Then, harness NVM’s install: $ nvm install 0.10 To switch to the 0.10 version, apply the use command. For example: $ nvm use 0.10 Alternative Multiversion Systems Alternatives to Nave and NVM include the following: neco • (https://github.com/kuno/neco) n • (https://github.com/visionmedia/n)
  • 17. Chapter 1 ■ Setting up Node.js and Other Essentials 7 Checking the Installation To test your installation, run the following commands in your Terminal app (command line cmd.exe in Windows): $ node -v $ npm -v You should see the latest versions of Node.js and NPM that you just downloaded and installed, as shown in Figure 1-3. Figure 1-3. Checking Node.js and NPM installations That’s it! You now have Node.js and NPM installed, and you should be ready to dig deeper into using the platform. The simplest way to run Node.js is through its virtual environment, which is often called read–eval–print–loop, or REPL. Node.js Console (REPL) Like most platforms/languages (e.g., Java, Python, Ruby, and PHP), Node.js comes with a virtual environment: REPL. Using this shell program, we can execute pretty much any Node.js/JavaScript code. It’s even possible to include modules and work with the file system! Other REPL use cases involve controlling nodecopters (http://nodecopter.com/) and debugging remote servers (more about this in Chapter 10). To start the console, run the following command in your terminal: $ node
  • 18. Chapter 1 ■ Setting up Node.js and Other Essentials 8 The prompt should change from $ to (or something else, depending on your shell). From this prompt, we can run any JavaScript/Node.js (akin to the Chrome Developer Tools console) we want. For example: 1+1 Hello+ +World a=1;b=2;a+b 17+29/2*7 f = function(x) {return x*2} f(b) The result of the previous snippet is shown in Figure 1-4. Figure 1-4. Executing JavaScript in Node.js REPL There are slight deviations in ECMAScript implementations in Node.js and browsers such as the Chrome Developer Tools console. For example, {}+{} is '[object Object][object Object]' in Node.js REPL, whereas the same code is NaN in the Chrome console because of the automatic semicolon insertion (ASI) feature. However, for the most part, Node.js REPL and the Chrome/Firefox consoles are similar. Launching Node.js Scripts To start a Node.js script from a file, simply run $ node filename—for example, $ node program.js. If all we need is a quick set of statements, there’s a -e option that allows us to run inline JavaScript/Node.js—for example, $ node -e console.log(new Date());.
  • 19. Chapter 1 ■ Setting up Node.js and Other Essentials 9 If the Node.js program uses environmental variables, it’s possible to set them right before the node command. For example: $ NODE_ENV=production API_KEY=442CC1FE-4333-46CE-80EE-6705A1896832 node server.js Preparing your code for production is discussed later in Chapter 10. Node.js Basics and Syntax Node.js was built on top of the Google Chrome V8 engine and its ECMAScript, which means most of the Node.js syntax is similar to front-end JavaScript (another implementation of ECMAScript), including objects, functions, and methods. In this section, we look at some of the most important aspects; let’s call them Node.js/JavaScript fundamentals: Loose typing • Buffer—Node.js super data type • Object literal notation • Functions • Arrays • Prototypal nature • Conventions • Loose Typing Automatic typecasting works well most of the time. It’s a great feature that saves a lot of time and mental energy! There are only a few types of primitives: String • Number (both integer and real) • Boolean • Undefined • Null • RegExp • Everything else is an object (i.e., mutable keyed collections, read Stackoverflow on “What does immutable mean?” ,1 if in doubt). Also, in JavaScript, there are String, Number, and Boolean objects that contain helpers for the primitives, as follows: 'a' === new String('a') //false but 1 http://stackoverflow.com/questions/3200211/what-does-immutable-mean
  • 20. Chapter 1 ■ Setting up Node.js and Other Essentials 10 'a' === new String('a').toString() //true or 'a' == new String('a') //true By the way, == performs automatic typecasting whereas === does not. Buffer—Node.js Super Data Type Buffer is a Node.js addition to four primitives (boolean, string, number, and RegExp) and all-encompassing objects (array and functions are also objects) in front-end JavaScript. Think of buffers as extremely efficient data stores. In fact, Node.js tries to use buffers any time it can, such as when reading from file systems and when receiving packets over the network. Object Literal Notation Object notation is super readable and compact: var obj = { color: green, type: suv, owner: { ... } } Remember, functions are objects: var obj = function () { this.color: green, this.type: suv, this.owner: { ... } } Functions In Node.js (as well as in JavaScript), functions are first-class citizens, and we treat them as variables, because they are objects! Yes, functions can even have properties/attributes. First, let’s learn how to define a function. Define/Create a Function The three most common ways to define/create a function are to use a named expression, an anonymous expression assigned to a variable, or both. The following is an example of a named expression: function f () { console.log('Hi'); return true; }
  • 21. Chapter 1 ■ Setting up Node.js and Other Essentials 11 An anonymous function expression assigned to a variable looks as follows (note that it must precede the invocation, because the function is not hoisted, unlike the previous example): var f = function () { console.log('Hi'); return true; } The following is an example of both approaches: var f = function f () { console.log('Hi'); return true; } A function with a property (remember, functions are just objects that can be invoked/initialized) is as follows: var f = function () {console.log('Boo');} f.boo = 1; f(); //outputs Boo console.log(f.boo); //outputs 1 Note ■ ■  The return keyword is optional. When it is omitted, the function returns undefined on invocation. Pass Functions as Parameters JavaScript treats functions like any other objects, so we can pass them to other functions as parameters (usually, callbacks in Node.js): var convertNum = function (num) { return num + 10; } var processNum = function (num, fn) { return fn(num); } processNum(10, convertNum); Function Invocation vs. Expression The function definition is as follows: function f () {};
  • 22. Chapter 1 ■ Setting up Node.js and Other Essentials 12 On the other hand, the function invocation looks like f(); Expression, because it resolves to some value (which could be a number, string, object, or boolean), is as follows: function f() {return false;} f(); A statement looks like function f(a) {console.log(a);} Arrays Arrays are also objects that have some special methods inherited from the Array.prototype2 global object. Nevertheless, JavaScript arrays are not real arrays; instead, they are objects with unique integer (usually 0 based) keys. var arr = []; var arr2 = [1, Hi, {a:2}, function () {console.log('boo');}]; var arr3 = new Array(); var arr4 = new Array(1,Hi, {a:2}, function () {console.log('boo');}); Prototypal Nature There are no classes in JavaScript because objects inherit directly from other objects, which is called prototypal inheritance. There are a few types of inheritance patterns in JavaScript: Classical • Pseudoclassical • Functional • This is an example of the functional inheritance pattern: var user = function (ops) { return { firstName: ops.name || 'John' , lastName: ops.name || 'Doe' , email: ops.email || 'test@test.com' , name: function() { return this.firstName + this.lastName} } } var agency = function(ops) { ops = ops || {} var agency = user(ops) agency.customers = ops.customers || 0 agency.isAgency = true return agency } 2 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
  • 23. Chapter 1 ■ Setting up Node.js and Other Essentials 13 Conventions It’s important to follow the most common language conventions. Some of them are listed here: Semicolons • camelCase • Naming • Commas • Indentations • Whitespace • These JavaScript/Node.js conventions (with semicolons being an exception) are stylistic and highly preferential. They don’t impact the execution; however, it’s strongly suggested that you follow one style consistently, especially if you are a developer working in teams and/or on open-source projects. Some open-source projects might not accept pull requests if they contain semicolons (e.g., NPM) or if they don’t use comma-first style (e.g., request). Semicolons The use of semicolons is optional, except for two cases: 1. In for loop construction: for (var i=0; i++; in) 2. When a new line starts with parentheses, such as when using an immediately invoked function expression (IIFE): ;(function(){...}()) camelCase camelCase is the main naming pattern in JavaScript, except for class names, which are CapitalCamelCase. An example follows: var MainView = Backbone.View.extend({...}) var mainView = new MainView() Naming _ and $ are perfectly legitimate characters for literals (jQuery and Underscore libraries use them a lot). Private methods and attributes start with _ (and it does nothing by itself!). Commas An example of a comma-first approach is as follows: var obj = { firstName: John , lastName: Smith , email: johnsmith@gmail.com }
  • 24. Chapter 1 ■ Setting up Node.js and Other Essentials 14 Indentation Indentation is usually done using either a tab, or four- or two-space indentation, with supporting camps split almost religiously between the two options. Whitespace Usually, there is a space before and after the =, +, {, and } symbols. There is no space on invocation (e.g., arr.push(1);), but there’s a space when we define an anonymous function: function () {}. Node.js Globals and Reserved Keywords Despite being modeled after one standard, Node.js and browser JavaScript differ when it comes to globals. This was done intentionally because when var is omitted, browser JavaScript leaks variables infamously to the global space, thus polluting it. This has been dubbed as one of the bad parts of JavaScript in the canonical book JavaScript: The Good Parts by Douglas Crockford (2008 O’Reilly). As you might know, in browser JavaScript we have a window object. However, in Node.js, it is absent (obviously we don’t deal with a browser window), but developers are provided with new objects/keywords: • process • global • module.exports and exports So, let’s take a look at the main differences between Node.js and JavaScript. Node.js Process Information Each Node.js script that runs is, in essence, a process. For example, ps aux | grep 'node' outputs all Node.js programs running on a machine. Conveniently, developers can access useful process information in code with the process object (e.g., node -e console.log(process.pid)), as shown in Figure 1-5.
  • 25. Chapter 1 ■ Setting up Node.js and Other Essentials 15 Accessing Global Scope in Node.js As you know, browser JavaScript, by default, puts everything into its global scope. On the other hand, Node.js was designed to behave differently, with everything being local by default. In case we need to access globals, there is a global object. And, when we need to export something, we should do so explicitly. In a sense, the window object from front-end/browser JavaScript metamorphosed into a combination of global and process objects. Needless to say, the document object, which represents the DOM (Document Object Model) of the web page, is nonexistent in Node.js. Exporting and Importing Modules Another bad part in browser JavaScript is that there is no way to include modules. Scripts are supposed to be linked together using a different language (HTML), but dependency management is lacking. CommonJS (http://www.commonjs.org/) and RequireJS (http://requirejs.org/) solve this problem with the AJAX-y approach. Node.js borrowed many things from the CommonJS concept. To export an object in Node.js, use exports.name = object;. An example follows: var messages = { find: function(req, res, next) { ... }, add: function(req, res, next) { ... }, format: 'title | date | author' } exports.messages = messages; Figure 1-5. Node.js process examples using pid (process ID) and cwd (current working directory)
  • 26. Chapter 1 ■ Setting up Node.js and Other Essentials 16 While in the file where we import the aforementioned script (assuming the path and the file name is route/messages.js), write the following: var messages = require('./routes/messages.js'); However, sometimes it’s more fitting to invoke a constructor, such as when we attach properties to the Express.js app (which is explained in detail in Express.js FUNdamentals: An Essential Overview of Express.js [2013], http://webapplog.com/express-js-fundamentals/). In this case, module.exports is needed: module.exports = function(app) { app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); return app; } In the file that includes the previous sample module, write ... var app = express(); var config = require('./config/index.js'); app = config(app); ... The more succinct code is var = express(); require('./config/index.js')(app);. The most common mistake when including modules is creating a wrong path to the file. For core Node.js modules, use the name without any path—for example, require('name'). The same goes for modules in the node_modules folder (more on this when we examine NPM later in the chapter). For all other files (i.e., not modules), use . with or without a file extension. An example follows: var keys = require('./keys.js'), messages = require('./routes/messages.js'); In addition, for including files, it’s possible to use longer statements with __dirname and path.join()—for example, require(path.join(__dirname, ,'routes', 'messages'));. This is a recommended approach, because path.join() will produce a path with valid slashes (forward or backward depending on your OS). If require() points to a folder, Node.js attempts to read the index.js file in that folder. __dirname vs. process.cwd __dirname is an absolute path to the file in which the global variable is called, whereas process.cwd is an absolute path to the process that runs the script. The latter might not be the same as the former if we started the program from a different folder, such as $ node ./code/program.js.
  • 27. Chapter 1 ■ Setting up Node.js and Other Essentials 17 Browser Application Programming Interface Helpers There are myriad helper functions in Node.js from the browser JavaScript application programming interface (API). The most useful come from String, Array, and Math objects. To make you aware of their existence, or to remind you, here is a list of the most common functions and their meanings: • Array • some() and every(): assertions for array items • join() and concat(): convertion to a string • pop(), push(), shift(), and unshift(): working with stacks and queues • map(): model mapping for array items • filter(): querying array items • sort(): ordering items • reduce(), reduceRight(): computing • slice(): copying • splice(): removing • indexOf(): lookups of finding the value in the array • reverse(): reversing the order The • in operator: iteration over array items • Math • random(): random real number less than one • String • substr() and substring(): extracting substrings • length: length of the string • indexOf(): index of finding the value in the string • split(): converting the string to an array In addition, we have setInterval(), setTimeout(), forEach(), and console methods in Node.js. For the complete list of methods and examples, visit the following sites: • String (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects/String) • Array (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects/Array) • Math (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects/Math)
  • 28. Chapter 1 ■ Setting up Node.js and Other Essentials 18 Node.js Core Modules Unlike other programming technologies, Node.js doesn’t come with a heavy standard library. The core modules of node.js are a bare minimum, and the rest can be cherry-picked via the NPM registry. The main core modules, classes, methods, and events include the following: • http (http://nodejs.org/api/http.html#http_http) • util (http://nodejs.org/api/util.html) • querystring (http://nodejs.org/api/querystring.html) • url (http://nodejs.org/api/url.html) • fs (http://nodejs.org/api/fs.html) http (http://nodejs.org/api/http.html) http is the main module responsible for the Node.js HTTP server. The main methods are as follows: • http.createServer(): returns a new web server object • http.listen(): begins accepting connections on the specified port and hostname • http.createClient(): is a client and makes requests to other servers • http.ServerRequest(): passes incoming requests to request handlers • data: emitted when a part of the message body is received • end: emitted exactly once for each request • request.method(): the request method as a string • request.url(): request URL string • http.ServerResponse(): creates this object internally by an HTTP server — not by the user— and is used as an output of request handlers • response.writeHead(): sends a response header to the request • response.write(): sends a response body • response.end(): sends and ends a response body util (http://nodejs.org/api/util.html) The util module provides utilities for debugging. One method is as follows: • util.inspect(): returns a string representation of an object, which is useful for debugging querystring (http://nodejs.org/api/querystring.html) The querystring module provides utilities for dealing with query strings. Some of the methods include the following: • querystring.stringify(): serializes an object to a query string • querystring.parse(): deserializes a query string to an object
  • 29. Chapter 1 ■ Setting up Node.js and Other Essentials 19 url (http://nodejs.org/api/url.html) The url module has utilities for URL resolution and parsing. One method is as follows: • parse(): takes a URL string and returns an object fs (http://nodejs.org/api/fs.html) fs handles file system operations such as reading to and writing from files. There are synchronous and asynchronous methods in the library. Some of the methods include the following: • fs.readFile(): reads files asynchronously • fs.writeFile(): writes data to files asynchronously There is no need to install or download core modules. To include them in your application, all you need is to use the following syntax: var http = require('http'); A list of noncore modules is found at the following locations: npmjs.org • (https://npmjs.org): for the NPM registry GitHub hosted list • (https://github.com/joyent/node/wiki/Modules): for Node.js modules maintained by Joyent nodetoolbox.com • (http://nodetoolbox.com/): for a registry based on stats Nipster • (http://eirikb.github.com/nipster/): for NPM search tools for Node.js Node tracking ( • http://nodejsmodules.org): for a registry based on GitHub stats If you want to know how to code your own modules, take a look at the article “Your First Node.js Module3 .” Handy Node.js Utilities Although the core of the Node.js platform was, intentionally, kept small, it has some essential utilities, including the following: • Crypto(http://nodejs.org/api/crypto.html): has randomizer, MD5, HMAC-SHA1, and other algorithms • Path(http://nodejs.org/api/path.html): handles system paths • String decoder(http://nodejs.org/api/string_decoder.html): decodes to and from buffer and string types The method we use throughout is path.join and it concatenates the path using an appropriate folder separator (/ or ). 3 http://cnnr.me/blog/2012/05/27/your-first-node-dot-js-module/
  • 30. Chapter 1 ■ Setting up Node.js and Other Essentials 20 Reading to and Writing from the File System in Node.js Reading from files is done via the core fs module (http://nodejs.org/api/fs.html). There are two sets of reading methods: async and sync. In most cases, developers should use async methods, such as fs.readFile: var fs = require('fs'); var path = require('path'); fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, function (err, data) { if (err) throw err; console.log(data); }); To write to the file, execute the following: var fs = require('fs'); fs.writeFile('message.txt', 'Hello World!', function (err) { if (err) throw err; console.log('Writing is done.'); }); Streaming Data in Node.js Streaming data is a phrase that means an application processes the data while it’s still receiving it. This feature is useful for extra large datasets such as video or database migrations. Here’s a basic example of using streams that output the binary file content back: var fs = require('fs'); fs.createReadStream('./data/customers.csv').pipe(process.stdout); By default, Node.js uses buffers for streams. For more immersive instruction, take a look at stream-adventure (http://npmjs.org/stream-adventure) and Stream Handbook (https://github.com/substack/stream-handbook). Installing Node.js Modules with NPM NPM comes with the Node.js platform and allows for seamless Node.js package management. The way npm install works is similar to Git in the way it traverses the working tree to find a current project (https://npmjs.org/doc/ files/npm-folders.html). For starters, keep in mind that we need either the package.json file or the node_modules folder to install modules locally with $ npm install name. For example, $ npm install superagent; in the program. js write: var superagent = require('superagent');. The best thing about NPM is that it keeps all the dependencies local, so if module A uses module B v1.3, and module C uses module B v2.0 (with breaking changes compared with v1.3), both A and C will have their own localized copies of different versions of B. This proves to be a more superior strategy than that of Ruby and other platforms that use global installations by default. The best practice is not to include a node_modules folder in the Git repository when the project is a module that is supposed to be used in other applications. However, it’s recommended to include node_modules for deployable applications to prevent breakage caused by unfortunate dependency updates. Note ■ ■  The NPM creator likes to call it npm (lowercase, http://npmjs.org/doc/misc/npm-faq.html).
  • 31. Chapter 1 ■ Setting up Node.js and Other Essentials 21 Taming Callbacks in Node.js Callbacks (https://github.com/maxogden/art-of-node) are able to make Node.js code asynchronous, yet programmers unfamiliar with JavaScript, who work with Java or PHP, might be surprised when they see Node.js code described on Callback Hell (http://callbackhell.com/): fs.readdir(source, function(err, files) { if (err) { console.log('Error finding files: ' + err) } else { files.forEach(function(filename, fileIndex) { console.log(filename) gm(source + filename).size(function(err, values) { if (err) { console.log('Error identifying file size: ' + err) } else { console.log(filename + ' : ' + values) aspect = (values.width / values.height) widths.forEach(function(width, widthIndex) { height = Math.round(width / aspect) console.log('resizing ' + filename + 'to ' + height + 'x' + height) this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) { if (err) console.log('Error writing file: ' + err) }) }.bind(this)) } }) }) } }) There’s nothing to be afraid of here as long as two-space indentation is used. ;-) However, callback code can be rewritten with the use of event emitters or promises, or by using the async library. Hello World Server with HTTP Node.js Module Although, Node.js can be used for a wide variety of tasks, it’s used primarily for building web applications. Node.js thrives in the network as a result of its asynchronous nature and built-in modules such as net and http. Here’s a quintessential Hello World example in which we create a server object, define the request handler (function with req and res arguments), pass some data back to the recipient, and start up the whole thing (hello.js): var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); Let’s break it down a bit (if you know this already, skip to the next section). The following loads the core http module for the server (more on the modules later): var http = require('http');
  • 32. Chapter 1 ■ Setting up Node.js and Other Essentials 22 This snippet below creates a server with a callback function which contains the response handler code: var server = http.createServer(function (req, res) { To set the right header and status code, use the following: res.writeHead(200, {'Content-Type': 'text/plain'}); To output Hello World with the line end symbol, use res.end('Hello Worldn'); }); The req and res arguments have all the information about a given HTTP request and response correspondingly. In addition, req and res can be used as streams (see previous section). To make the server accept requests, use the following: ... listen(1337, '127.0.0.1'); From the folder in which you have server.js, launch in your terminal the following command: $ node server.js Open localhost:1337 or 127.0.0.1:1337 or any other address you see in the terminal as a result of the console.log() function and you should see Hello World in a browser. To shut down the server, press Control + c (on Mac OS X). Note ■ ■  The name of the main file could be different from server.js (e.g., index.js or app.js). In case you need to launch the app.js file, just use $ node app.js. Debugging Node.js Programs Modern-day software developers, especially those who use compiled languages such as Java, get accustomed to rich tool sets for debugging purposes. Back in the day, before JavaScript and AJAX apps were starting to gain momentum (~2005–2007), the only way to debug was to put a bunch of alert() statements everywhere. Now, there are amazing environments such as Chrome Developer Tools and Firefox Firebug! Also, because Node.js has a lot of things in common with the browser JavaScript environment, we have plenty of options for debugging in Node.js, including the following: • Core Node.js Debugger: a nongraphic user interface (non-GUI) minimalistic tool that works everywhere • Node Inspector: port of Google Chrome Developer Tools WebStorm and other IDEs (covered in the next section) • Core Node.js Debugger The best debugger is console.log(), because it doesn’t break/interrupt the flow, and it is fast and informative. However, to use it, we first need to know where to put it. Sometimes, we just don’t know where to put the logs! Other times, we need to see the call stack and orient ourselves in the async code a bit more. To do this, put debugger statements in your code and use $ node debug program.js to start the debugging process (http://nodejs.org/api/debugger.html).
  • 33. Chapter 1 ■ Setting up Node.js and Other Essentials 23 For example, the Hello World from the previous section can be enhanced with debugger in two places: when an instance is created and when a request is made (hello-debug.js): var http = require('http'); debugger; http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); debugger; res.end('Hello Worldn'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); Now, if we run the previous snippet (hello-debug.js), just like we did earlier ($ node hello-debug.js), nothing changes, because we need to use $ node debug hello-debug.js. And only then, the execution halts at the first line, and then again on the next debugger statement if we use the cont command. The main node debug commands are as follows: • next, n: step to the next statement • cont, c: continue until the next debugger/break point • step, s: step inside the function call • out, o: step outside the function call • watch(expression): watch the expression The full list of commands is available through the help command or on the official web site (http://nodejs.org/api/debugger.html). So, in our example (hello-debug.js), after we start the debugger client and execute cont or c twice (first for the first line and second for our debugger on the second line), the server will be up and running. After that, we can open the browser at (http://localhost:1337/) or execute $ curl (http://localhost:1337/) in the Terminal/ Command line, and the debugger client stops inside the request handler (line 5). Now we can use repl and console. log(req) to inspect the HTTP response object dynamically. Debugging with Node Inspector The built-in Node.js debugger client is extensive, but it’s not intuitive because of the lack of a GUI. Therefore, for a more developer-friendly interface than the core Node.js debugger provides, node-inspector (https://github.com/ node-inspector/node-inspector) comes to the rescue! To download and install Node Inspector, we use our beloved NPM in the global mode (-g or --global): $ npm install -g node-inspector Then, we start Node Inspector with the following (Figure 1-6): $ node-inspector
  • 34. Chapter 1 ■ Setting up Node.js and Other Essentials 24 Now start the program in a new terminal window/tab/session with --debug or --debug-brk flags (not just debug; Figure 1-7). For example: $ node --debug-brk hello-debug.js or $ node --debug hello-debug.js Figure 1-6. Running the Node Inspector tool
  • 35. Chapter 1 ■ Setting up Node.js and Other Essentials 25 Open http://127.0.0.1:8080/debug?port=5858 or http://localhost:8080/debug?port=5858 in Chrome (it must be Chrome and not another browser because Node Inspector uses the Web Developer Tools interface). You should be able to see the program halted at a break point. Clicking the blue play button resumes the execution, as shown in Figure 1-8. Figure 1-7. Running node server in --debug mode
  • 36. Chapter 1 ■ Setting up Node.js and Other Essentials 26 If we let the server run and open http://localhost:1337/ in a new browser tab, this action pauses the execution on the second break point, which is inside the request handler. From here, we can use Node Inspector’s right GUI and add a res watcher (Figure 1-9), which is way better than the terminal window output! Figure 1-8. Resuming execution in Node Inspector
  • 37. Chapter 1 ■ Setting up Node.js and Other Essentials 27 In addition, we can follow the call stack, explore scope variables, and execute any Node.js command in the console tab (Figure 1-10)! Figure 1-9. Inspecting res object in Node Inspector
  • 38. Chapter 1 ■ Setting up Node.js and Other Essentials 28 Node.js IDEs and Code Editors OneofthebestthingsaboutNode.jsisthatyoudon’tneedtocompilethecode,becauseit’sloadedintomemoryand interpretedbytheplatform!Therefore,alightweighttexteditorishighlyrecommended,suchasSublimeText(Figure1-11), vs.afull-blownIDE.However,ifyouarealreadyfamiliarandcomfortablewiththeIDEofyourchoice,suchasEclipse (http://www.eclipse.org/),NetBeans(http://netbeans.org/),orAptana(http://aptana.com/),feelfreetostickwithit. Figure 1-10. Writing to response (i.e., the res object) from the Node Inspector console Figure 1-11. Sublime Text code editor home page
  • 39. Chapter 1 ■ Setting up Node.js and Other Essentials 29 The following is a list of the most popular text editors and IDEs used in web development: • TextMate (http://macromates.com/): Mac OS X version only, free 30-day trial for v1.5, dubbed The Missing Editor for Mac OS X • Sublime Text (http://www.sublimetext.com/): Mac OS X and Windows versions are available, an even better alternative to TextMate, with an unlimited evaluation period • Coda (http://panic.com/coda/): an all-in-one editor with an FTP browser and preview, has support for development with an iPad • Aptana Studio (http://aptana.com/): a full-size IDE with a built-in terminal and many other tools • Notepad ++ (http://notepad-plus-plus.org/): a free, Windows-only lightweight text editor with the support of many languages • WebStorm IDE (http://www.jetbrains.com/webstorm/): a feature-rich IDE that allows for Node.js debugging, developed by JetBrains and marketed as “the smartest JavaScript IDE” (Figure 1-12) Figure 1-12. WebStorm IDE home page For most developers, a simple code editor such as Sublime Text 2, TextMate, or Emacs is good enough. However, for programmers who are used to working in IDEs, there’s WebStorm by JetBrains (http://www.jetbrains.com/webstorm). For an example of the WebStorm work space, see Figure 1-13.
  • 40. Chapter 1 ■ Setting up Node.js and Other Essentials 30 Watching for File Changes If you are familiar with watching for file changes or it’s not an issue for you, feel free to skip this section. Node.js applications are stored in memory, and if we make changes to the source code, we need to restart the process (i.e., node). We do this manually by killing the process and starting a new one (Control + c on Macs and Ctrl + c on Windows). However, it’s faster for development if this constant sequence of restarts is automated. There are brilliant tools that leverage the watch method from the core Node.js fs module and restart servers when we save changes from an editor: forever ( • http://npmjs.org/forever) (GitHub, http://github.com/nodejitsu/forever) usually used in production (we examine this topic in Chapter 11) node-dev( • https://npmjs.org/package/node-dev)(GitHub, https://github.com/fgnass/node-dev) Figure 1-13. Webstorm IDE work space
  • 41. Chapter 1 ■ Setting up Node.js and Other Essentials 31 nodemon ( • https://npmjs.org/package/nodemon) (GitHub, https://github.com/remy/nodemon) supervisor ( • https://npmjs.org/package/supervisor) (GitHub, https://github.com/ isaacs/node-supervisor) up ( • https://npmjs.org/package/up) (GitHub, https://github.com/LearnBoost/up), now a deprecated module Any one of these tools is as easy to use as installing globally with $ npm install -g node-dev, then running the Node.js script with $ node-dev program.js. Just replace node-dev with another module name.☺ For a comparison between these tools, refer to Comparison: Tools to Automate Restarting Node.js Server After Code Changes (http://strongloop.com/strongblog/comparison-tools-to-automate-restarting-node-js- server-after-code-changes-forever-nodemon-nodesupervisor-nodedev/). Tip ■ ■  It’s good to know that Express.js reloads a template file for every new request by default. So, no server restart is necessary. However, we can cache templates by enabling the view cache setting. For more Express.js setting, take a look at Pro Express.js 4 [2014, Apress]. Summary In this chapter, we explored Installing Node.js and NPM, and launching Node.js scripts from the command line. We also looked at the essential concepts of Node.js syntax and the platform. Last, lists of Node.js IDEs and libraries for development were provided. In the next chapter, we dive deep into using the most popular Node.js framework for creating web apps.
  • 42. 33 Chapter 2 Using Express.js 4 to Create Node.js Web Apps It’s only logical that, by using frameworks, software engineers become more productive and can achieve results faster. Often, the results are of a better quality because the frameworks are used and maintained by many other developers and contributors. Even if developers build everything from scratch, they end up with their own framework in the end. It’s just a very customized one! Node.js is a relatively young platform when it comes to frameworks (unlike Ruby or Java), but there’s already a leader that has become a de facto standard used in the majority of Node.js projects: Express.js. Express.js is an amazing framework for Node.js projects, and it’s used in the majority of web apps, which is why this second chapter is dedicated to getting started with this framework. In this chapter we cover the following topics, which serve as an introduction to Express.js: What Express.js is • How Express.js works • Express.js Installation • Express.js scaffolding (command-line tool) • The Blog Project overview • Express.js 4 Hello World example • What Is Express.js? Express.js is a web framework based on the core Node.js http module and Connect (http://www.senchalabs.org/ connect/) components. The components are called middleware and they are the cornerstones of the framework philosophy configuration over convention. In other words, Express.js systems are highly configurable, which allows developers to pick freely whatever libraries they need for a particular project. For these reasons, the Express.js framework leads to flexibility and high customization in the development of web applications. If you write serious apps using only core Node.js modules (refer to the following snippet for an example), you most likely find yourself reinventing the wheel by writing the same code continually for similar tasks, such as the following: Parsing of HTTP request bodies • Parsing of cookies • Managing sessions •
  • 43. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps 34 Organizing routes with a chain of • if conditions based on URL paths and HTTP methods of the requests Determining proper response headers based on data types • To illustrate my point, here is an example of a two-route representational state transfer: http://en.wikipedia.org/wiki/Representational_state_transfer. (REST) API server, i.e., we have only two end points and they are also called routes. In this application, we use only core Node.js modules for server functions. A single “userland”/external native MongoDB driver module is used for persistence. This example is taken from beginner-friendly Rapid Prototyping with JS (http://rpjs.co/): Agile JavaScript Development by Azat Mardan [2013]: var http = require('http'); var util = require('util'); var querystring = require('querystring'); var mongo = require('mongodb'); var host = process.env.MONGOHQ_URL || 'mongodb://@127.0.0.1:27017'; //MONGOHQ_URL=mongodb://user:pass@server.mongohq.com/db_name mongo.Db.connect(host, function(error, client) { if (error) throw error; var collection = new mongo.Collection( client, 'test_collection' ); var app = http.createServer( function (request, response) { if ( request.method === 'GET' request.url === '/messages/list.json' ) { collection.find().toArray(function(error, results) { response.writeHead( 200, {'Content-Type': 'text/plain'} ); console.dir(results); response.end(JSON.stringify(results)); }); }; if ( request.method === POST request.url === /messages/create.json ) { request.on('data', function(data) { collection.insert( querystring.parse(data.toString('utf-8')), {safe: true}, function(error, obj) { if (error) throw error; response.end(JSON.stringify(obj)); }
  • 44. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps 35 ); }); }; }); var port = process.env.PORT || 5000; app.listen(port); }) As you can see, developers have to do a lot of manual work themselves, such as interpreting HTTP methods and URLs into routes, and parsing input and output data. Express.js solves these and many other problems as abstraction and code organization. The framework provides a model-view-controller-like (MVC-like) structure for your web apps with a clear separation of concerns (views, routes, models). For the models (M in MVC), we need to use Mongoose (http://mongoosejs.com/) or Sequelize (http://sequelizejs.com/) libraries in addition to Express.js— more on this later in the book in Chapter 7. In this chapter we’ll cover the basics of Express.js. Built on top this framework, Express.js applications can vary from bare-bones, back-end-only REST APIs to full-blown, highly scalable, full-stack with jade-browser (https://npmjs.org/package/ jade-browser) and Socket.IO (http://socket.io/), real-time web apps. To give some analogies to developers who are familiar with Ruby—Express.js is often seen as Sinatra, which has a very different approach to the Ruby on Rails framework. Express.js and Sinatra promote the configurability while Ruby on Rails convention over configuration. Although Express.js is the most starred library on NPM (as of May 2014), and the most mature and used Node. js framework, the playing field is still relatively level with many different frameworks, and new ones are released every month. Some of them, such as Meteor (http://meteor.com/) and DerbyJS (http://derbyjs.com/), show an interesting trend in attempts to merge front-end and back-end code bases. For a handpicked list of Node.js frameworks, refer to the Node Framework (http://nodeframework.com/) resource. When evaluating a Node.js framework for your project, use these easy steps to guide you: Build a sample app which is usually provided by the creators of frameworks on GitHub or • official web sites. See how the app feels in terms of styles and patterns. Consider the type of application you’re building: prototype, production app, minimum viable • product (MVP), small scale, large scale, and so on. Consider the libraries already familiar to you and determine whether you can or plan to reuse • them, and whether your framework plays nicely with them. Provide out-of-the-box solutions: template engines, database object-relational mapping (http://en.wikipedia.org/wiki/ Object-relational_mapping) libraries (ORMs) / drivers, cascading style sheets (http://en.wikipedia.org/wiki/Cascading_Style_Sheets) (CSS) frameworks. Consider the nature of your application: REST API (with a separate front-end client), a • traditional web app, or a traditional web app with REST API end points (such as Blog). Consider whether you need the support of reactive templates with WebSocket from the • get-go. (the Meteor framework, anyone?) Evaluate the number of stars and follows on NPM and GitHub to judge the popularity of the • framework. More popular typically means more blog posts, books, screencasts, tutorials, and programmers exist; less popular means this is a newer framework, a niche/custom choice, or a poor choice. With newer frameworks, there is a greater chance that contributing back to them will be valued, so pick your comfortable spot. Evaluate NPM, GitHub pages, and a framework’s website for the presence of good API • documentation with examples or open issues/bugs. If there are more than a few hundred, depending on popularity, this may not be a good sign. Also, determine the date of the last commit on the GitHub repository. Anything older than six months is not a good sign.
  • 45. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps 36 How Express.js Works Express.js usually has an entry point—aka, a main file. Most of the time, this is the file that we start with the node command; or export as a module, in some cases. And in this file, we do the following: 1. Include third-party dependencies as well as our own modules, such as controllers, utilities, helpers, and models 2. Configure Express.js app settings such as template engine and its file extensions 3. Connect to databases such as MongoDB, Redis, or MySQL (optional) 4. Define middleware such as error handlers, static files folder, cookies, and other parsers 5. Define routes 6. Start the app 7. Export the app as a module (optional) When the Express.js app is running, it’s listening to requests. Each incoming request is processed according to a defined chain of middleware and routes, starting from top to bottom. This aspect is important in controlling the execution flow. For example, routes/middleware that are higher in the file have precedence over the lower definitions. Because we can have multiple middleware functions processing each HTTP request, some of the functions are in the middle (hence the name middleware). Here are some examples of middleware purposes: 1. Parse cookie information and put it in req object for following middleware/routes 2. Parse parameters from the URL and put it in req object for following middleware/routes 3. Get the information from the database based on the value of the parameter if the user is authorized (cookie/session) and put it in req object for following middleware/routes 4. Authorize users/requests, or not. 5. Display the data and end the response Express.js Installation The Express.js package comes in two flavors: 1. express-generator: a global NPM package that provides the command-line tool for rapid app creation (scaffolding) 2. express: a local package module in your Node.js app’s node_modules folder Express.js Version Before we proceed with installations, let’s check the Express.js versions. We’ll use an exact version 4.1.2 to avoid confusion resulting from potential future changes to the Express.js skeleton-generating mechanism and the module API. For the Express.js Generator, which is a separate module, we’ll use version 4.0.0, which is compatible with Express.js 4.x. If you have a version other than 4.0.0 ($ express -V to check), you can uninstall it using $ sudo npm uninstall -g express-generator. Or $ sudo npm uninstall -g express for Express.js 2.x and 3.x. Before, version 4.x, Express.js Generator was a part of the Express.js module itself. After you’ve uninstalled the older versions, install the proper version with the next section’s commands.
  • 46. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps 37 Express.js Generator To install the Express.js Generator as global package, run $ npm install -g express-generator@4.0.0 from anywhere on your computer. This downloads and links the $ express terminal command to the proper path, so that later we can access its command-line interface (CLI) for the creation of new apps. Note ■ ■ For Max OS X and Linux users, if there is an error installing globally, most likely your system requires root/ administrator rights to write to the folder. In this case, $ sudo npm install -g express-generator@4.0.0 might be needed. Refer to Chapter 1 for more information on changing NPM ownership. Of course, we can be more vague and tell NPM to install the latest version of express-generator: $ npm install –g express-generator. But in this case your results might be inconsistent with the book’s examples. The Figure 2-1 shows us results of running the aforementioned command. Please notice the path in Figure 2-1: /usr/local/lib/node_modules/express-generator. This is where, on Max OS X / Linux systems, NPM puts global modules by default. We verify the availability of Express.js CLI by running $ express –V. Figure 2-1. The result of running NPM with -g and $ express -V Local Express.js For the local Express.js 4.1.2 module installation, let’s create a new folder express-cli somewhere on your computer: $ mkdir express-cli. This will be our project folder for the chapter. Now we can open it with $ cd express-cli. When we are inside the project folder, we can create package.json manually in a text editor or with the $ npm init terminal command (Figure 2-2).
  • 47. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps 38 The following is an example of the package.json file with vanilla $ npm init options: { name: express-cli, version: 0.0.1, description: , main: index.js, scripts: { test: echo Error: no test specified exit 1 }, author: , license: BSD } Lastly, we install the module using NPM: $ npm install express@4.1.2 --save Or, if we want to be less specific, which is not recommended for this example, use: $ npm install express Note ■ ■  If you attempt to run the aforementioned $ npm install express command without the package.json file or the node_modules folder, the smart NPM will traverse up the directory tree to the folder that has either of these two things. This behavior mimics Git’s logic somewhat. For more information on the NPM installation algorithm, please refer to the official documentation at https://npmjs.org/doc/folders.html. Figure 2-2. The result of running $ npm init
  • 48. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps 39 Alternatively, we can update the package.json file by specifying the dependency (express: 4.1.2 or express: 4.x) and run $ npm install. The following is the package.json file with an added Express.js v4.1.2 dependency (the latest as of May 2014): { name: expressjsguide, version: 0.0.1, description: , main: index.js, scripts: { test: echo Error: no test specified exit 1 }, dependencies: { express: 4.1.2 }, author: , license: BSD } $ npm install In Figure 2-3, we show the result of install Express.js v4.1.2 locally, into the node_modules folder. Please notice the path after the express@4.1.2 string in Figure 2-3 is now local and not global, as in the case of express-generator. Figure 2-3. The result of running $ npm install If you want to install Express.js to an existing project and save the dependency (smart thing to do!) into the package.json file, which is already present in that project’s folder, run $ npm install express@4.1.2 --save. To double-check the installation of Express.js and its dependencies, we can run the $ npm ls command, as shown in Figure 2-4.
  • 49. Another Random Scribd Document with Unrelated Content
  • 50. hotel spoke of him continually. Lord Markham was now the authority whom she quoted on all subjects. Even Domenico said “meelord” with a relish. And as for the Durants, their enthusiasm was boundless. Tasie, not yet quite recovered from the excitement of Constance’s arrival, lost her self- control altogether when Markham appeared. It was so good of him to come to church, she said; such an example for the people at the hotels! And so nice to lose so little time in coming to call upon papa. Of course, papa, as the clergyman, would have called upon him as soon as it was known where he was staying. But it was so pretty of Lord Markham to conform to foreign ways and make the first visit. “We knew it must be your doing, Frances,” she said, with grateful delight. “But, indeed, it was not my doing. It is Constance who makes him come,” Frances cried. Constance, indeed, insisted upon his company everywhere. She took him not only to the Durants, but to the bungalow up among the olive woods, which they found in great excitement, and where the appearance of Lord Markham partially failed of its effect, a greater hero and stranger being there. George Gaunt, the General’s youngest son, the chief subject of his mother’s talk, the one of her children about whom she always had something to say, had arrived the day before, and in his presence even a living lord sank into a secondary place. Mrs Gaunt had been the first to see the little party coming along by the terraces of the olive woods. She had, long, long ago, formed plans in her imagination of what might ensue when George came home. She ran out to meet them with her hands extended. “Oh Frances, I am so glad to see you! Only fancy what has happened. George has come!” “I am so glad,” said Frances, who was the first. She was more used to the winding of those terraces, and then she had not so much to talk of as Constance and Markham. Her face lighted up with pleasure. “How happy you must be!” she said, kissing the old lady affectionately. “Is he well?” “Oh, wonderfully well; so much better than I could have hoped. George, George, where are you? Oh, my dear, I am so anxious that you should meet! I want you to like him,” Mrs Gaunt said. Almost for the first time there came a sting of pain to Frances’ heart. She had heard a great deal of George Gaunt. She had thought of him more than of any other stranger. She had wondered what he would be like, and smiled
  • 51. to herself at his mother’s too evident anxiety to bring them together, with a slight, not disagreeable flutter of interest in her own consciousness. And now here he was, and she was going away! It seemed a sort of spite of fortune, a tantalising of circumstances; though, to be sure, she did not know whether she should like him, or if Mrs Gaunt’s hopes might bear any fruit. Still, it was the only outlet her imagination had ever had, and it had amused and given her a pleasant fantastic glimpse now and then into something that might be more exciting than the calm round of every day. She stood on the little grassy terrace which surrounded the house, looking towards the open door, but not taking any step towards it, waiting for the hero to appear. The house was low and broad, with a veranda round it, planted in the midst of the olive groves, where there was a little clearing, and looking down upon the sea. Frances paused there, with her face towards the house, and saw coming out from under the shadow of the veranda, with a certain awkward celerity, the straight slim figure of the young Indian officer, his mother’s hero, and, in a visionary sense, her own. She did not advance—she could not tell why—but waited till he should come up, while his mother turned round, beckoning to him. This was how it was that Constance and Markham arrived upon the scene before the introduction was fully accomplished. Frances held out her hand, and he took it, coming forward; but already his eyes had travelled over her head to the other pair arriving, with a look of inquiry and surprise. He let Frances’ hand drop as soon as he had touched it, and turned towards the other, who was much more attractive than Frances. Constance, who missed nothing, gave him a glance, and then turned to his mother. “We brought our brother to see you,” she said (as Frances had not had presence of mind to do). “Lord Markham, Mrs Gaunt. But we have come at an inappropriate moment, when you are occupied.” “Oh no! It is so kind of you to come. This is my son George, Miss Waring. He arrived last night. I have so wanted him to meet——” She did not say Frances; but she looked at the little girl, who was quite eclipsed and in the background, and then hurriedly added, “your—family: whose name he knows, as such friends! And how kind of Lord Markham to come all this way!” She was not accustomed to lords, and the mother’s mind jumped at once to the vain, but so usual idea, that this lord, who had himself sought the acquaintance, might be of use to her son. She brought forward George, who
  • 52. was a little dazzled too; and it was not till the party had been swept into the veranda, where the family sat in the evening, that Mrs Gaunt became aware that Frances had followed, the last of the train, and had seated herself on the outskirts of the group, no one paying any heed to her. Even then, she was too much under the influence of the less known visitors to do anything to put this right. “I am delighted that you think me kind,” said Markham, in answer to the assurances which Mrs Gaunt kept repeating, not knowing what to say. “My step-father is not of that opinion at all. Neither will you be, I fear, when you know my mission. I have come for Frances.” “For Frances!” she cried, with a little suppressed scream of dismay. “Ah, I said you would not be of that opinion long,” Markham said. “Is Frances going away?” said the old General. “I don’t think we can stand that. Eh, George? that is not what your mother promised you. Frances is all we have got to remind us that we were young once. Waring must hear reason. He must not let her go away.” “Frances is going; but Constance stays,” interposed that young lady. “General, I hope you will adopt me in her stead.” “That I will,” said the old soldier; “that is, I will adopt you in addition, for we cannot give up Frances. Though, if it is only for a short visit, if you pledge yourself to bring her back again, I suppose we will have to give our consent.” “Not I,” said Mrs Gaunt under her breath. She whispered to her son, “Go and talk to her. This is not Frances; that is Frances,” leaning over his shoulder. George did not mean to shake off her hand; but he made a little impatient movement, and turned the other way to Constance, to whom he made some confused remark. All the conversation was about Frances; but she took no part in it, nor did any one turn to her to ask her own opinion. She sat on the edge of the veranda, half hidden by the luxuriant growth of a rose which covered one of the pillars, and looked out rather wistfully, it must be allowed, over the grey clouds of olives in the foreground, to the blue of the sea beyond. It was twilight under the shade of the veranda; but outside, a subdued daylight, on the turn towards night. The little talk about her was very flattering, but somehow it did not have the effect it might have had; for though they all
  • 53. spoke of her as of so much importance, they left her out with one consent. Not exactly with one consent. Mrs Gaunt, standing up, looking from one to another, hurt—though causelessly—beyond expression by the careless movement of her newly returned boy, would have gone to Frances, had she not been held by some magnetic attraction which emanated from the others —the lord who might be of use—the young lady, whose careless ease and self-confidence were dazzling to simple people. Neither the General nor his wife could realise that she was merely Frances’ sister, Waring’s daughter. She was the sister of Lord Markham. She was on another level altogether from the little girl who had been so pleasant to them all, and so sweet. They were very sorry that Frances was going away; but the other one required attention, had to be thought of, and put in the chief place. As for Frances, who knew them all so well, she would not mind. And thus even Mrs Gaunt directed her attention to the new-comer. Frances thought it was all very natural, and exactly what she wished. She was glad, very glad that they should take to Constance; that she should make friends with all the old friends who to herself had been so tender and kind. But there was one thing in which she could not help but feel a little disappointed, disconcerted, cast down. She had looked forward to George. She had thought of this new element in the quiet village life with a pleasant flutter of her heart. It had been natural to think of him as falling more or less to her own share, partly because it would be so in the fitness of things, she being the youngest of all the society—the girl, as he would be the boy; and partly because of his mother’s fond talk, which was full of innocent hints of her hopes. That George should come when she was just going away, was bad enough; but that they should have met like this, that he should have touched her hand almost without looking at her, that he should not have had the most momentary desire to make acquaintance with Frances, whose name he must have heard so often, that gave her a real pang. To be sure, it was only a pang of the imagination. She had not fallen in love with his photograph, which did not represent an Adonis; and it was something, half a brother, half a comrade, not (consciously) a lover, for which Frances had looked in him. But yet it gave her a very strange, painful, deserted sensation when she saw him look over her head at Constance, and felt her hand dropped as soon as taken. She smiled a little at herself, when she came to think of it, saying to herself that she knew very well Constance was far more charming, far more pretty than she, and that it was only natural she
  • 54. should take the first place. Frances was ever anxious to yield to her the first place. But she could not help that quiver of involuntary feeling. She was hurt, though it was all so natural. It was natural, too, that she should be hurt, and that nobody should take any notice—all the most everyday things in the world. George Gaunt came to the Palazzo next day. He came in the afternoon with his father, to be introduced to Waring; and he came again after dinner —for these neighbours did not entertain each other at the working-day meals, so to speak, but only in light ornamental ways, with cups of tea or black coffee—with both his parents to spend the evening. He was thin and of a slightly greenish tinge in his brownness, by reason of India and the illnesses he had gone through; but his slim figure had a look of power; and he had kind eyes, like his mother’s, under the hollows of his brows: not a handsome young man, yet not at all common or ordinary, with a soldier’s neatness and upright bearing. To see Markham beside him with his insignificant figure, his little round head tufted with sandy hair, his one- sided look with his glass in his eye, or his ear tilted up on the opposite side, was as good as a sermon upon race and its advantages. For Markham was the fifteenth lord; and the Gaunts were, it was understood, of as good as no family at all. Captain George from that first evening had neither ear nor eye for any one but Constance. He followed her about shyly wherever she moved; he stood over her when she sat down. He said little, for he was shy, poor fellow; yet he did sometimes hazard a remark, which was always subsidiary or responsive to something she had said. Mrs Gaunt’s distress at this subversion of all she had intended was great. She got Frances into a corner of the loggia while the others talked, and thrust upon her a pretty sandalwood box inlaid with ivory, one of those that George had brought from India. “It was always intended for you, dear,” she said. “Of course he could not venture to offer it himself.” “But, dear Mrs Gaunt,” said Frances, with a low laugh, in which all her little bitterness evaporated, “I don’t think he has so much as seen my face. I am sure he would not know me if we met in the road.” “Oh, my dear child,” cried poor Mrs Gaunt, “it has been such a disappointment to me. I have just cried my eyes out over it. To think you should not have taken to each other after all my dreams and hopes.”
  • 55. Frances laughed again; but she did not say that there had been no failure of interest on her side. She said, “I hope he will soon be quite strong and well. You will write and tell me about everybody.” “Indeed I will. Oh Frances, is it possible that you are going so soon? It does not seem natural that you should be going, and that your sister should stay.” “Not very natural,” said Frances, with a composure which was less natural still. “But since it is to be, I hope you will see as much of her as you can, dear Mrs Gaunt, and be as kind to her as you have been to me.” “Oh, my dear, there is little doubt that I shall see a great deal of her,” said the mother, with a glance towards the other group, of which Constance was the central figure. She was lying back in the big wicker-work chair; with the white hands and arms, which showed out of sleeves shorter than were usual in Bordighera, very visible in the dusk, accompanying her talk by lively gestures. The young captain stood like a sentinel a little behind her. His mother’s glance was half vexation and half pleasure. She thought it was a great thing for a girl to have secured the attentions of her boy, and a very sad thing for the girl who had not secured them. Any doubt that Constance might not be grateful, had not yet entered her thoughts. Frances, though she was so much less experienced, saw the matter in another light. “You must remember,” she said, “that she has been brought up very differently. She has been used to a great deal of admiration, Markham says.” “And now you will come in for that, and she must take what she can get here.” Mrs Gaunt’s tone when she said this showed that she felt, whoever was the loser, it would not be Constance. Frances shook her head. “It will be very different with me. And dear Mrs Gaunt, if Constance should not—do as you wish——” “My dear, I will not interfere. It never does any good when a mother interferes,” Mrs Gaunt said hurriedly. Her mind was incapable of pursuing the idea which Frances so timidly had endeavoured to suggest. And what could the girl do more? Next day she went away. Her father, pale and stern, took leave of her in the bookroom with an air of offence and displeasure which went to Frances’ heart. “I will not come to the station. You will have, no doubt, everybody at the station. I don’t like greetings in the market-places,” he said.
  • 56. “Papa,” said Frances, “Mariuccia knows everything. I am sure she will be careful. She says she will not trouble Constance more than is necessary. And I hope——” “Oh, we shall do very well, I don’t doubt.” “I hope you will forgive me, papa, for all I may have done wrong. I hope you will not miss me; that is, I hope—oh, I hope you will miss me a little, for it breaks my heart when you look at me like that.” “We shall do very well,” said Waring, not looking at her at all, “both you and I.” “And you have nothing to say to me, papa?” “Nothing—except that I hope you will like your new life and find everything pleasant. Good-bye, my dear; it is time you were going.” And that was all. Everybody was at the station, it was true, which made it no place for leave-takings; and Frances did not know that he watched the train from the loggia till the white plume of steam disappeared with a roar in the next of those many tunnels that spoil the beautiful Cornice road. Constance walked back in the midst of the Gaunts and Durants, looking, as she always did, the mistress of the situation. But neither did Frances, blotted out in the corner of the carriage, crying behind her veil and her handkerchief, leaving all she knew behind her, understand with what a tug at her heart Constance saw the familiar little ugly face of her brother for the last time at the carriage-window, and turned back to the deadly monotony of the shelter she had sought for herself, with a sense that everything was over, and she herself completely deserted, like a wreck upon a desolate shore. END OF THE FIRST VOLUME. PRINTED BY WILLIAM BLACKWOOD AND SONS.
  • 57. A HOUSE DIVIDED AGAINST ITSELF BY MRS OLIPHANT IN THREE VOLUMES VOL. II. WILLIAM BLACKWOOD AND SONS EDINBURGH AND LONDON MDCCCLXXXVI A HOUSE DIVIDED AGAINST ITSELF.
  • 58. CHAPTER XVII. “Yes, I hope you will come and see me often. Oh yes, I shall miss my sister; but then I shall have all the more of papa. Good night. Good night, Captain Gaunt. No; I don’t sketch; that was Frances. I don’t know the country either. It was my sister who knew it. I am quite ignorant and useless. Good night.” Waring, who was on the loggia, heard this in the clear tones of his only remaining companion. He heard her come in afterwards with a step more distinct than that of Frances, as her voice carried farther. He said to himself that everything was more distinct about this girl, and he was glad that she was coming, glad of some relief from the depression which overcame him against his will. She came across one room after another, and out upon the loggia, throwing herself down listlessly in the usurped chair. It did not occur to him that she was unaware of his presence, and he was surprised that she said nothing. But after a minute or two, there could be no doubt why it was that Constance did not speak. There was no loud outburst of emotion, but a low suppressed sound, which it was impossible to mistake. She said, after a moment, to herself, “What a fool I am!” But even this reflection did not stem the tide. A sensation of utter solitude had seized upon her. She was abandoned, among strangers; and though she had so much experience of the world, it was not of this world that Constance had any knowledge. Had she been left alone among a new tribe of people unknown to her, she would not have been afraid! Court or camp would have had no alarms for her; but the solitude, broken only by the occasional appearance of these rustic companions; the simple young soldier, who was going to bestow his heart upon her, an entirely undesired gift; the anxious mother, who was about to mount guard over her at a distance; the polite old beau in the background. Was it possible that the existence she knew had altogether receded from Constance, and left her with such companions alone? She was not thinking of her father, neither of himself nor of his possible presence, which was of little importance to her. After a while she sat upright and passed her handkerchief quickly over her face. “It is my own fault,” she said, still to herself; “I might have known.” “You don’t see, Constance, that I am here.”
  • 59. She started, and pulled herself up in a moment. “Oh, are you there, papa? No, I didn’t see you. I didn’t think of any one being here. Well, they are gone. Everybody came to see Frances off, as you divined. She bore up very well; but, of course, it was a little sad for her, leaving everything she knows.” “You were crying a minute ago, Constance.” “Was I? Oh, well, that was nothing. Girls cry, and it doesn’t mean much. You know women well enough to know that.” “Yes, I know women—enough to say the ordinary things about them,” said Waring; “but perhaps I don’t know you, which is of far more consequence just now.” “There is not much in me to know,” said the girl in a light voice. “I am just like other girls. I am apt to cry when I see people crying. Frances sobbed—like a little foolish thing; for why should she cry? She is going to see the world. Did you ever feel, when you came here first, a sort of horror seize upon you, as if—as if—as if you were lost in a savage wilderness, and would never see a human face again?” “No; I cannot say I ever felt that.” “No, to be sure,” cried Constance. “What ridiculous nonsense I am talking! A savage wilderness! with all these houses about, and the hotels on the beach. I mean—didn’t you feel as if you would like to run violently down a steep place into the sea?” Then she stopped, and laughed. “It was the swine that did that.” “It has never occurred to me to take that means of settling matters; and yet I understand you,” he said gravely. “You have made a mistake. You thought you were philosopher enough to give up the world; and it turns out that you are not. But you need not cry, for it is not too late. You can change your mind.” “I—change my mind! Not for the world, papa! Do you think I would give them the triumph of supposing that I could not do without them, that I was obliged to go back? Not for the world.” “I understand the sentiment,” he said. “Still, between these two conditions of mind, it is rather unfortunate for you, my dear. I do not see any middle course.”
  • 60. “Oh yes, there is a middle course. I can make myself very comfortable here; and that is what I mean to do. Papa, if you had not found it out, I should not have told you. I hope you are not offended?” “Oh no, I am not offended,” he said, with a short laugh. “It is perhaps a pity that everybody has been put to so much trouble for what gives you so little satisfaction. That is the worst of it; these mistakes affect so many others besides one’s self.” Constance evidently had a struggle with herself to accept this reproof; but she made no immediate reply. After a while: “Frances will be a little strange at first; but she will like it by-and-by; and it is only right she should have her share,” she said softly. “I have been wondering,” she went on, with a laugh that was somewhat forced, “whether mamma will respect her individuality at all; or if she will put her altogether into my place? I wonder if—that man I told you of, papa——” “Well, what of him?” said Waring, rather sharply. “I wonder if he will be turned over to Frances too? It would be droll. Mamma is not a person to give up any of her plans, if she can help it; and you have brought up Frances so very well, papa; she is so docile—and so obedient——” “You think she will accept your old lover, or your old wardrobe, or anything that offers? I don’t think she is so well brought up as that.” “I did not mean to insult my sister,” cried Constance, springing to her feet. “She is so well brought up, that she accepted whatever you chose to say to her, forgetting that she was a woman, that she was a lady.” Waring’s face grew scarlet in the darkness. “I hope,” he said, “that I am incapable of forgetting on any provocation that my daughter is a lady.” “You mean me!” she cried, breathless. “Oh, I can——” But here she stopped. “Papa,” she resumed, “what good will it do us to quarrel? I don’t want to quarrel. Instead of setting yourself against me because I am poor Con, and not Frances, whom you love—— Oh, I think you might be good to me just at this moment; for I am very lonely, and I don’t know what I am good for, and I think my heart will break.” She went to him quickly, and flung herself upon his shoulder, and cried. Waring was perhaps more embarrassed than touched by this appeal; but after all, she was his child, and he was sorry for her. He put his arm round her, and said a few soothing words. “You may be good for a great deal, if
  • 61. you choose,” he said; “and if you will believe me, my dear, you will find that by far the most amusing way. You have more capabilities than Frances; you are much better educated than she is—at least I suppose so, for she was not educated at all.” “How do you mean that it will be more amusing? I don’t expect to be amused; all that is over,” said Constance, in a dolorous tone. He was so much like her, that he paused for a moment to consider whether he should be angry, but decided against it, and laughed instead. “You are not complimentary,” he said. “What I mean is, that if you sit still and think over your deprivations, you will inevitably be miserable; whereas, if you exert yourself a little, and make the best of the situation, you will very likely extract something that is amusing out of it. I have seen it happen so often in my experience.” “Ah,” said Constance, considering. And then she withdrew from him and went back to her chair. “I thought, perhaps, you meant something more positive. There are perhaps possibilities: Frances would have thought it wrong to look out for amusement—that must have been because you trained her so.” “Not altogether. Frances does not require so much amusement as you do. It is so in everything. One individual wants more sleep, more food, more delight than others.” “Yes, yes,” she cried; “that is like me. Some people are more alive than others; that is what you mean, papa.” “I am not sure that it is what I mean; but if you like to take it so, I have no objection. And in that view, I recommend you to live, Constance. You will find it a great deal more amusing than to mope; and it will be much pleasanter to me.” “Yes,” she said, “I was considering. Perhaps what I mean will be not the same as what you mean. I will not do it in Frances’ way; but still I will take your advice, papa. I am sure you are right in what you say.” “I am glad you think so, my dear. If you cannot have everything you want, take what you can get. It is the only true philosophy.” “Then I will be a true philosopher,” she said, with a laugh. The laugh was more than a mere recovery of spirits. It broke out again after a little, as if with a sense of something irresistibly comic. “But I must not interfere too much with Mariuccia, it appears. She knows what you like better than I do.
  • 62. I am only to look wise when she submits her menu, as if I knew all about it. I am very good at looking as if I knew all about it. By the way, do you know there is no piano? I should like to have a piano, if I might.” “That will not be very difficult,” he said. “Can you play?” At which she laughed once more, with all her easy confidence restored. “You shall hear, when you get me a piano. Thanks, papa; you have quite restored me to myself. I can’t knit you socks, like Frances; and I am not so clever about the mayonnaises; but still I am not altogether devoid of intellect. And now, we completely understand each other. Good night.” “This is sudden,” he said. “Good night, if you think it is time for that ceremony.” “It is time for me; I am a little tired; and I have got some alterations to make in my room, now that—now that—at present when I am quite settled and see my way.” He did not understand what she meant, and he did not inquire. It was of very little consequence. Indeed it was perhaps well that she should go and leave him to think of everything. It was not a month yet since the day when he had met that idiot Mannering on the road. To be sure, there was no proof that the idiot Mannering was the cause of all that had ensued. But at least it was he who had first disturbed the calm which Waring hoped was to have been eternal. He sat down to think, almost grateful to Constance for taking herself away. He thought a little of Frances hurrying along into the unknown, the first great journey she had ever taken—and such a journey, away from everything and everybody she knew. Poor little Fan! he thought a little about her; but he thought a great deal about himself. Would it ever be possible to return to that peace which had been so profound, which had ceased to appear capable of disturbance? The circumstances were all very different now. Frances, who would think it her duty to write to him often, was henceforth to be her mother’s companion, reflecting, no doubt, the sentiments of a mind, to escape from the companionship of which he had given up the world and (almost) his own species. And Constance, though she had elected to be his companion, would no doubt all the same write to her mother; and everything that he did and said, and all the circumstances of his life, would thus be laid open. He felt an impatience beyond words of that dutifulness of women, that propriety in which girls are trained, which makes them write letters. Why should they write letters? But it was
  • 63. impossible to prevent it. His wife would become a sort of distant witness of everything he did. She would know what he liked for dinner, the wine he preferred, how many baths he took. To describe how this thought annoyed him would be impossible. He had forgotten to warn Frances that her father was not to be discussed with my lady. But what was the use of saying anything, when letters would come and go continually from the one house to the other? And he would be compelled to put up with it, though nothing could be more unpleasant. If these girls had been boys, this would not have happened. It was perhaps the first time Waring had felt himself within reach of such a wish, for boys were far more objectionable to his fine taste than girls, gave more trouble, and were less agreeable to have about one. In the present circumstances, however, he could not but feel they would have been less embarrassing. Constance might grow tired, indeed, of that unprofitable exercise of letter-writing. But Frances, he felt sure, would in all cases be dutiful, and would not grow tired. She would write to him perhaps (he shivered) every day; at least every week; and she would think it her duty to tell him everything that happened, and she would require that he should reply. But this, except once or twice, perhaps, to let her down easily, he was resolved that nothing should induce him to do. Constance was neither tired nor sleepy when she went to her room. She had never betrayed the consciousness in any way, being high-bred and courteous when it did not interfere with her comfort to be so; yet she had divined that Frances had given up her room to her. This would have touched the heart of many people, but to Constance it was almost an irritation. She could not think why her sister had done it, except with that intention of self- martyrdom with which so many good people exasperate their neighbours. She would have been quite as comfortable in the blue room, and she would have liked it better. Now that Frances was safely gone and her feelings could not be hurt any more, Constance had set her heart upon altering it to her own pleasure, making it bear no longer the impress of Frances’ mind, but of her own. She took down a number of the pictures which Frances had thought so much of, and softly pulled the things about, and changed it more than any one could have supposed a room could be changed. Then she sat down to think. The depression which had seized upon her when she had felt that all was over, that the door was closed upon her, and no place of repentance any longer possible, did not return at first. Her father’s words, which she understood in a sense not intended by him, gave her a great deal
  • 64. of amusement as she thought them over. She did not conceal from herself the fact that there might ensue circumstances in which she should quote them to him to justify herself. “Frances does not require so much amusement as you do. One individual requires more sleep, more food, more delight than another.” She laid this dangerous saying up in her mind with much glee, laughing to herself under her breath: “If you cannot get what you want, you must take what you can get.” How astounded he would be if it should ever be necessary to put him in mind of these dogmas—which were so true! Her father’s arguments, indeed, which were so well meant, did not suit the case of Constance. She had been in a better state of mind when she had felt herself to awake, as it were, on the edge of this desert, into which, in her impatience, she had flung herself, and saw that there was no escape for her, that she had been taken at her word, that she was to be permitted to work out her own will, and that no one would forcibly interfere to restore all her delights, to smooth the way for her to return. She had expected this, if not consciously, yet with a strong unexpressed conviction. But when she had seen Markham’s face disappear, and realised that he was gone, actually gone, and had left her to exist as she could in the wilderness to which she had flown, her young perverse soul had been swept as by a tempest. After a while, when she had gone through that little interview with her father, when she had executed her little revolution, and had seated herself in the quiet of the early night to think again over the whole matter, the pang returned, as every pang does. It was not yet ten o’clock, the hour at which she might have been setting out to a succession of entertainments under her mother’s wing; but she had nothing better to amuse her than to alter the arrangement of a few old chairs, to draw aside a faded curtain, and then to betake herself to bed, though it was too early to sleep. There were sounds of voices still audible without—people singing, gossiping, enjoying, on the stone benches on the Punto, just those same delights of society which happy people on the verge of a new season were beginning to enjoy. But Constance did not feel much sympathy with the villagers, who were foreigners, whom she felt to be annoying and intrusive, making a noise under her windows, when, as it so happened, she had nothing to do but to go to sleep. When she looked out from the window and saw the pale sky spreading clear over the sea, she could think of nothing but Frances rushing along through the night, with Markham taking such care of her, hastening to
  • 65. London, to all that was worth living for. No doubt that little thing was still crying in her corner, in her folly and ignorance regretting her village. Oh, if they could but have changed places! To think of sitting opposite to Markham, with the soft night air blowing in her face, devouring the way, seeing the little towns flash past, the morning dawn upon France, the long levels of the flat country sweep along, then Paris, London, at last! She shut the persiani almost violently with a hand that trembled, and looked round the four walls which shut her in, with again an impulse almost of despair. She felt like a wild creature newly caged, shut in there, to be kept within bolts and bars, to pace up and down, and beat against the walls of her prison, and never more to go free. But this fit being more violent, did not go so deep as the unspeakable sense of loneliness which had overwhelmed her soul at first. She sprang up from it with the buoyancy of her age, and said to herself what her father had said: “If you cannot get what you want, you must take what you can get.” There was yet a little amusement to be had out of this arid place. She had her father’s sanction for making use of her opportunities; anything was better than to mope; and for her it was a necessity to live. She laughed a little under her breath once more, as she came back to this more reassuring thought, and so lay down in her sister’s bed with a satisfaction in the thought that it had not taken her any trouble to supplant Frances, and a mischievous smile about the corners of her mouth; although, after all, the thought of the travellers came over her again as she closed her eyes, and she ended by crying herself to sleep.
  • 66. CHAPTER XVIII. Captain Gaunt called next day to bring, he said, a message from his mother. She sent Mr Waring a newspaper which she thought he might like to see, an English weekly newspaper, which some of her correspondents had sent her, in which there was an article—— He did not give a very clear account of this, nor make it distinctly apparent why Waring should be specially interested; and as a matter of fact, the newspaper found its way to the waste-paper basket, and interested nobody. But, no doubt, Mrs Gaunt’s intentions had been excellent. When the young soldier arrived, there was a carriage at the door, and Constance had her hat on. “We are going,” she said, “to San Remo, to see about a piano. Do you know San Remo? Oh, I forgot you are as much a stranger as I am; you don’t know anything. What a good thing that there are two ignorant persons! We will keep each other in countenance, and they will be compelled to make all kinds of expeditions to show us everything.” “That will be a wonderful chance for me,” said the young man, “for nobody would take so much trouble for me alone.” “How can you tell that? Miss Tasie, I should think, would be an excellent cicerone,” said Constance. She said it with a light laugh of suggestion, meaning to imply, though, of course, she had said nothing, that Tasie would be too happy to put herself at Captain Gaunt’s disposition; a suggestion which he, too, received with a laugh—for this is one of the points upon which both boys and girls are always ungenerous. “And failing Miss Tasie,” said Constance, “suppose you come with papa and me? They say it is a pretty drive. They say, of course, that everything here is lovely, and that the Riviera is paradise. Do you find it so?” “I can fancy circumstances in which I should find it so,” said the young soldier. “Ah, yes; every one can do that. I can fancy circumstances in which Bond Street would be paradise—oh, very easily! It is not far from paradise at any time.” “That is a heaven of which I know very little, Miss Waring.”
  • 67. “Ah, then, you must learn. The true Elysian fields are in London in May. If you don’t know that, you can form no idea of happiness. An exile from all delights gives you the information, and you may be sure it is true.” “Why, then, Miss Waring, if you think so——” “Am I here? Oh, that is easily explained. I have a sister.” “Yes, I know.” “Ah, I understand you have heard a great deal about my sister. I suffer here from being compared with her. I am not nearly so good, so wise, as Frances. But is that my fault, Captain Gaunt? You are impartial; you are a new-comer. If I could, I would, be as nice as Frances, don’t you believe?” The young man gave Constance a look, which, indeed, she expected, and said with confusion, “I don’t see—any need for improvement,” and blushed as near crimson as was possible over the greenish brown of his Indian colour. Constance for her part did not blush. She laughed, and made him an almost imperceptible curtsey. The ways of flirtation are not original, and all the parallels of the early encounters might be stereotyped, as everybody knows. “You are very amiable,” she said; “but then you don’t know Frances, and your opinion, accordingly, is less valuable. I did not ask you, however, to believe me to be equal to my sister, but only to believe that I would be as nice if I could. However, all that is no explanation. We have a mother, you know, in England. We are, unfortunately, that sad thing, a household divided against itself.” Captain Gaunt was not prepared for such confidences. He grew still a little browner with embarrassment, and muttered something about being very sorry, not knowing what to say. “Oh, there is not very much to be sorry about. Papa enjoys himself in his way here, and mamma is very happy at home. The only thing is that we must each have our turn, you know—that is only fair. So Frances has gone to mamma, and here am I in Bordighera. We are each dreadfully out of our element. Her friends condemn me, to begin with, as if it were my fault that I am not like her; and my friends, perhaps—— But no; I don’t think so. Frances is so good, so nice, so everything a girl ought to be.”
  • 68. At this she laughed softly again; and young Gaunt’s consciousness that his mother’s much vaunted Frances was the sort of girl to please old ladies rather than young men, a prim, little, smooth, correct maiden, with not the least “go” in her, took additional force and certainty. Whereas—— But he had no words in which to express his sense of the advantages on the other side. “You must find it,” he said, knowing nothing more original to say, “dreadfully dull living here.” “I have not found anything as yet; I have only just come. I am no more than a few days older than you are. We can compare notes as time goes on. But perhaps you don’t mean to stay very long in these abodes of the blest?” “I don’t know that I did intend it. But I shall stay now as long as ever I can,” said the young man. Then—for he was shy—he added hastily, “It is a long time since I have seen my people, and they like to have me.” “Naturally. But you need not have spoiled what looked like a very pretty compliment by adding that. Perhaps you didn’t mean it for a compliment? Oh, I don’t mind at all. It is much more original, if you didn’t mean it. Compliments are such common coin. But I don’t pretend to despise them, as some girls do; and I don’t like to see them spoiled,” Constance said seriously. The young man looked at her with consternation. After a while, his moustache expanded into a laugh, but it was a confused laugh, and he did not understand. Still less did he know how to reply. Constance had been used to sharper wits, who took her at half a word; and she was half angry to be thus obliged to explain. “We are going to San Remo, as I told you,” she said. “I am waiting for my father. We are going to look for a piano. Frances is not musical, so there is no piano in the house. You must come too, and give your advice. Oh, are you ready, papa? Captain Gaunt, who does not know San Remo, and who does know music, is coming with us to give us his advice.” The young soldier stammered forth that to go to San Remo was the thing he most desired in the world. “But I don’t think my advice will be good for much,” he said, conscientiously. “I do a little on the violin; but as for pretending to be a judge of a piano——” “Come; we are all ready,” said Constance, leading the way.
  • 69. Waring had to let the young fellow precede him, to see him get into the carriage without any articulate murmur. As a matter of fact, a sort of stupor seized the father, altogether unaccustomed to be the victim of accidents. Frances might have lived by his side till she was fifty before she would have thought of inviting a stranger to be of their party—a stranger, a young man, which was a class of being with which Waring had little patience, a young soldier, proverbially frivolous, and occupied with foolish matters. Young Gaunt respectfully left to his senior the place beside Constance; but he placed himself opposite to her, and kept his eyes upon her with a devout attention, which Waring would have thought ridiculous had he not been irritated by it. The young fellow was a great deal too much absorbed to contribute much to the amusement of the party; and it irritated Waring beyond measure to see his eyes gleam from under his eyebrows, opening wider with delight, half closing with laughter, the ends of his moustache going up to his ears. Waring, an impartial spectator, was not so much impressed by his daughter’s wit. He thought he had heard a great deal of the same before, or even better, surely better, for he could recollect that he had in his day been charmed by a similar treatment, which must have been much lighter in touch, much less commonplace in subject, because—he was charmed. Thus we argue in our generations. In the meantime, young Gaunt, though he had not been without some experience, looked at Constance from under his brows, and listened as if to the utterances of the gods. If only they could have had it all to themselves; if only the old father had been out of the way! The sunshine, the sea, the beautiful colour, the unexpected vision round every corner of another and another picturesque cluster of towns and roofs; all that charm and variety which give to Italy above every country on earth the admixture of human interest, the endless chain of association which adds a grace to natural beauty, made very little impression upon this young pair. She would have been amused and delighted by the exercise of her own power, and he would have been enthralled by her beauty, and what he considered her wit and high spirits, had their progress been along the dullest streets. It was only Waring’s eyes, disgusted by the prospect before him of his daughter’s little artifices, and young Gaunt’s imbecile subjection, which turned with any special consciousness to the varying blues of the sea, to the endless developments of the landscape. Flirtation is one of the last things in the world to brook a spectator. Its little absurdities, which are so delightful
  • 70. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com