Practical Nodejs Building Realworld Scalable Web Apps 1st Edition Azat Mardan Auth
Practical Nodejs Building Realworld Scalable Web Apps 1st Edition Azat Mardan Auth
Practical Nodejs Building Realworld Scalable Web Apps 1st Edition Azat Mardan Auth
Practical Nodejs Building Realworld Scalable Web Apps 1st Edition Azat Mardan Auth
1. Practical Nodejs Building Realworld Scalable Web
Apps 1st Edition Azat Mardan Auth download
https://ebookbell.com/product/practical-nodejs-building-
realworld-scalable-web-apps-1st-edition-azat-mardan-auth-4929380
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Practical Nodejs Building Realworld Scalable Web Apps 2nd Ed Mardan
https://ebookbell.com/product/practical-nodejs-building-realworld-
scalable-web-apps-2nd-ed-mardan-55892676
Learn Nodejs By Building 6 Projects Build Six Practical And
Instructive Nodejs Projects Solutions
https://ebookbell.com/product/learn-nodejs-by-building-6-projects-
build-six-practical-and-instructive-nodejs-projects-solutions-55918930
Practical Bot Development Designing And Building Bots With Nodejs And
Microsoft Bot Framework 1st Ed Szymon Rozga
https://ebookbell.com/product/practical-bot-development-designing-and-
building-bots-with-nodejs-and-microsoft-bot-framework-1st-ed-szymon-
rozga-7146708
Nodejs Cookbook 5th Edition Practical Recipes For Building Serverside
Web Applications With Nodejs 22 Bethany Griggs Manuel Spigolon
https://ebookbell.com/product/nodejs-cookbook-5th-edition-practical-
recipes-for-building-serverside-web-applications-with-
nodejs-22-bethany-griggs-manuel-spigolon-90720098
3. 9 Practical Nodejs Projects 1st Patrick Catanzariti Paul Orac
https://ebookbell.com/product/9-practical-nodejs-projects-1st-patrick-
catanzariti-paul-orac-10806894
Nodejs The Right Way Practical Serverside Javascript That Scales 1st
Edition Jim R Wilson
https://ebookbell.com/product/nodejs-the-right-way-practical-
serverside-javascript-that-scales-1st-edition-jim-r-wilson-4946042
Nodejs 8 The Right Way Practical Serverside Javascript That Scales 1st
Edition Jim Wilson
https://ebookbell.com/product/nodejs-8-the-right-way-practical-
serverside-javascript-that-scales-1st-edition-jim-wilson-7012680
Nodejs Web Development Serverside Web Development Made Easy With Node
14 Using Practical Examples 5th Edition David Herron
https://ebookbell.com/product/nodejs-web-development-serverside-web-
development-made-easy-with-node-14-using-practical-examples-5th-
edition-david-herron-11734758
Essential Cryptography For Javascript Developers A Practical Guide To
Leveraging Common Cryptographic Operations In Nodejs And The Browser
1st Edition Alessandro Segala
https://ebookbell.com/product/essential-cryptography-for-javascript-
developers-a-practical-guide-to-leveraging-common-cryptographic-
operations-in-nodejs-and-the-browser-1st-edition-alessandro-
segala-53025618
6. 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.
7. 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
8. 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.
9. ■ 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.
10. ■ 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.
11. ■ 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!.
12. 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)
13. 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).
14. 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
15. 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.
16. 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
17. 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)
18. 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
19. 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());.
20. 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
21. 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;
}
22. 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 () {};
23. 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
24. 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
}
25. 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.
26. 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)
27. 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.
28. 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)
29. 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
30. 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/
31. 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).
32. 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');
33. 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).
34. 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
35. 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
36. 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
37. 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
38. 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
39. 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
40. 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.
41. 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
42. 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.
43. 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
•
44. 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));
}
45. 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.
46. 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.
47. 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).
48. 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
49. 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.
50. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
40
Express.js Scaffolding
So far, we’ve covered Expres.js installation. When it comes to prototyping, it’s vital to be able to get started quickly with
the solid app skeleton, which is why many modern frameworks provide some type of scaffolding. Now is the time to
explore its rapid app creation mechanism— Express.js Generator!
Comparable with Ruby on Rails and many other web frameworks, Express.js comes with a CLI for jump-starting
your development process. The CLI generates a basic foundation for the most common cases.
If you followed the global installation instructions in the installation section, you should be able to see the
version number 4.0.0 if you run $ express -V from anywhere on your machine. If we type $ express -h or $
express --help, we should get the list of available options and their usage. The list of options is broken down below
to serve readers as a reference.
To generate a skeleton Express.js app, we need to run a terminal command— express
[options] [dir|appname]—the options for which are the following:
• -e, --ejs: add EJS (http://embeddedjs.com/) engine support (by default, Jade
(http://jade-lang.com/tutorial/) is used)
• -H, --hogan: add Hogan.js engine support
• -c engine, --css engine: add stylesheet engine support, such as LESS
(http://lesscss.org/), Stylus (http://learnboost.github.io/stylus/) or Compass
(http://compass-style.org/) (by default, plain CSS is used)
• -f, --force: force app generation on a nonempty directory
If the dir/appname option is omitted, Express.js creates files using the current folder as the base for the project.
Otherwise, the application is in the folder with the name provided.
Now that we’re clear with the command and its options, let’s go step by step to create an app with the scaffolding:
1. Check the Express.js version, because the app-generating code is prone to changes.
2. Execute the scaffolding command with options.
3. Run the application locally.
Figure 2-4. The result of running $ npm ls
51. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
41
4. Understand the different sections, such as routes, middleware, and configuration.
5. Peek into the Jade template (more on this in Chapter 3).
Express.js Command-Line Interface
Now we can use the CLI to spawn new Express.js apps. For example, to create an app with Stylus support, type the
following:
$ express -c styl express-styl
Then, as the instructions in the terminal tell us (Figure 2-5), type:
$ cd express-styl npm install
$ DEBUG=my-application ./bin/www
Figure 2-5. The result of using Express.js Generator
Open the browser of your choice at http://localhost:3000.
If you don’t have computer in front of your right now, here’s the full code of express-styl/app.js using Express.
js Generator v4.0.0:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
52. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
42
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
53. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
43
Routes in Express.js
When you open express-styl/app.js, you see two routes in the middle:
app.use('/', routes);
app.use('/users', users);
The first one basically takes care of all the requests to the home page, such as http://localhost:3000/. The
second takes care of requests to /users, such as http://localhost:3000/users. Both of the routes process URLs in a
case-insensitive manner and in a same way as with trailing slashes.
By default, Express.js doesn’t allow developers to route by query string arguments, such as the following:
GET: www.webapplog.com/?id=10233
GET: www.webapplog.com/about/?author=10239
GET: www.webapplog.com/books/?id=10ref=201
However, it’s trivial to write your own middleware. It might look like this:
app.use(function (req, res, next) {
if (req.query.id) {
// process the id, then call next() when done
else if (req.query.author) {
// same approach as with id
else if (req.query.id req.query.ref) {
// process when id and ref present
} else {
next();
}
});
app.get('/about', function (req, res, next) {
// this code is executed after the query string middleware
});
The request handler itself (index.js, in this case) is straightforward. Everything from the HTTP request is in req
and it writes results to the response in res:
exports.list = function(req, res){
res.send('respond with a resource');
};
Middleware as the Backbone of Express.js
Each line/statement above the routes in app.js is middleware:
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//...
app.use(favicon());
54. Chapter 2 ■ Using Express.js 4 to Create Node.js Web Apps
44
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
The middleware includes pass-through functions that either do something useful or add something helpful to the
request as it travels along each of them. For example, bodyParser() and cookieParser() add HTTP request payload
(req.body) and parsed cookie data (req.cookie), respectively. And in our app.js, app.use(logger('dev')); is
tirelessly printing in the terminal pretty logs for each request. In Express.js 3.x, many of these middleware were part of
the Express.js module, but not in version 4.x. For this reason, the generator declared and included, and we installed
additional modules like static-favicon, morgan, cookie-parser and body-parser.
Configuration of an Express.js App
Here is how we define configuration statements in a typical Express.js app (the app.js file):
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
And in bin/www:
app.set('port', process.env.PORT || 3000);
An ordinary setting involves a name, such as views, and a value, such as path.join(__dirname, 'views'), a
path to the folder where the templates/views live.
Sometimes there is more than one way to define a certain setting. For example, app.enable('trust proxy') for
Boolean flags is identical (aka, sugar-coating) to app.set('trust proxy', true). The Chapter 11 explains why we
might need to trust proxy.
Jade Is Haml for Express.js/Node.js
The Jade template engine is akin to the Ruby on Rails’ Haml in the way it uses whitespace and indentation, such as
layout.jade:
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
Other than that, it’s possible to use a full-blown JavaScript code inside of Jade templates with the - prefix. More
information on Jade and Handlebars template engines is in Chapter 4.
56. Mrs. Orr.
O really!
A Young Man.
Bring the score!
Mrs. Egerton.
I can't help wishing, though, that he would see
And do for others as he does for us.
(They stand listening)
Egerton.
Just let your minds go out about the mountains.
(A pause)
Have you had too much punch, or what's the trouble?
(Laughter)
Mrs. Orr.
Just hear how joyous hearted! Promise me——
Mrs. Egerton.
(In alarm)
He's telling them of the pines!
Mrs. Orr.
What would you do?
Mrs. Egerton.
57. (Beckons to the Butler, who is passing)
Tell Donald that I wish to speak with——
Mrs. Orr.
Stop!
Egerton.
It's something, gentlemen, that we all have need of.
Mrs. Orr.
Dear, if you ever dare tell Donald this
And pass this ghastly whisper to his heart,
I'll be the Secret Lady of the Pines;
I'll whisper something. What if Donald knew
Who's kept the strike afoot? The great unknown
Contributor to the Citizens' Relief?
Who had twelve hundred dollars in the bank,
A present from a Christmas long ago?
Twelve hundred and twelve hundred——!
Mrs. Egerton.
It can't be!
Mrs. Orr.
We bankers' wives——
Mrs. Egerton.
A mere coincidence.
Mrs. Orr.
It's not; he's checked it out. So! If you care
58. Nothing for Donald's happiness, I do.
(She leaves Mrs. Egerton standing near the pines. Other
ladies have begun to come in)
Ralph Ardsley.
What's underneath the forest?
Mrs. Orr.
(With a strange smile, calling back)
I really will.
Egerton.
You give it up?
Mrs. Egerton.
My noble, noble son!
General Chadbourne.
He's waiting, gentlemen, till he finds the mine.
Egerton.
The man of parts!
Several.
Of course.
Egerton.
That's why I can't
Take you down now. But when I find the mine
And get the gold to puddling in the pots,
59. If I can find me plastic metal workers
That I can mould and hammer while they mould
And hammer out my vision on the walls,
I'll show you through some subterranean chambers
Will set your eyes a-dazzle. In the dark,
Lit by the torches in the miners' caps,
You'll see the world of metals moving up
Through human hands as here you see the tree.
That's why my basement isn't finished yet.
Cries.
Good luck! Good luck!
Egerton.
I hope you'll be alive.
(He leaves the group and comes forward)
Governor Braddock.
Magnificent conception.
Bishop Hardbrooke.
A great man.
Egerton.
(To the Butler)
Call them in, Charles. Have all of them come in.
Governor Braddock.
Metals, then trees, then mills, then books and pictures.
Bishop Hardbrooke.
60. Raw matter on its spiral up to spirit.
Egerton.
While we're at riddles, gentlemen——
(Ladies come in, centre and forward right)
Egerton.
Come right in.
If you'll allow me, friends, suppose you stand
Where you can have my forest in your eye.
(He arranges them to face right)
I don't see, ladies, how you ever endure
The dulness of these males. We've been at riddles.
Come in. I've kept my best wine for the last.
(He steps back near the door, centre right)
Suppose you'd made an Adam out of clay,
Worked years to get it to your satisfaction,
And now you're looking at it, hands all washed
And mind confronting, weighing what's been done.
Suddenly you're aware of something standing by you
That whispers in your left ear: 'Make a wish
Within the power of God.' What would it be?
Bishop Hardbrooke.
To see it walk about the garden, brother.
Egerton.
Suppose your Adam was a pine-wood, Bishop,
That couldn't walk.
61. Mrs. Orr.
(Ardently)
Then just to hear it breathe.
Egerton.
A woman's intuition!
(Looks to see who it is)
Sylvia Orr!
Bishop Hardbrooke.
Sylva a forest.
Egerton.
An old friend of mine.
(He gives a signal to some one)
A clear day in the pine-wood.
(Suddenly the hall is beautifully illuminated)
Guests.
Ah!
Egerton.
With clouds,
The dawn just breaking.
(The hall becomes gray and shadowy)
62. Ancient silence.
Mrs. Egerton.
(Half in terror)
Donald!
Egerton.
Let us be quiet now.
(The silence is broken by the ringing of a telephone bell
in the room forward left)
General Chadbourne.
Ah!
Mrs. Orr.
(Across to Mrs. Egerton)
Don't you dare!
(The Butler goes out to answer the telephone)
Governor Braddock.
This age of bells and whistles.
General Chadbourne.
(Comes forward and takes his stand near the door
forward left)
Just in time!
Egerton.
They don't concern me. We are far away
63. With quiet all about us and the woods.
(The silence is intense)
General Chadbourne.
(Rehearsing his speech)
... And it gives me pleasure to announce to you
Upon the occasion of the opening
Of your new mansion, Colonel Egerton,
This bit of news, sir, from the military;
And I offer it with our congratulations:
The strike is over;
The men have yielded and have gone to work.
And all's been done without one——
(Enter the Butler hurriedly)
General Chadbourne.
Here I am.
Butler.
(Passing him)
For Mr. Egerton.
General Chadbourne.
No!
Butler.
(In a low voice over the crowd)
Mr. Egerton!
General Chadbourne.
64. Isn't that Captain Haskell?
Butler.
Mr. Jergens.
(Egerton comes forward, making his way through the
crowd)
General Chadbourne.
Butler!
(The Butler goes to him and they talk)
Ralph Ardsley.
(Calls after Egerton as he goes out left)
Good luck!
(Calls to Chadbourne)
This probably ends it.
Governor Braddock.
What's your opinion of these mysteries, Bishop?
Bishop Hardbrooke.
I'm one of those that simply stand and wait.
Governor Braddock.
You don't believe in modern miracles.
Bishop Hardbrooke.
There are miracles and miracles, Governor Braddock.
65. I try to keep elastic in these things,
Steering a middle course with open mind.
Ralph Ardsley.
(Calls to Chadbourne)
Needed just this to crown the time we're having.
Bishop Hardbrooke.
We are living in an age in many ways
Without a parallel. I sometimes think—
If I may say it not too seriously—
Of those last days we read of when the world
Goes on its way unconscious of the end.
We give and take in marriage, eat and drink,
And meet our friends in social intercourse,
And all the while a Spirit walks beside us,
Enters our homes and writes upon our walls.
There are whispers everywhere if we could hear them;
And some of them grow louder with the days;
And pools of quiet ruffle and show storms.
You, Governor, feel the popular unrest
As it manifests itself in politics,
The shift of parties and of principles,
Rocks that we used to think would never change.
And brother Egerton in industry;
He feels it.
Egerton.
(Appearing at the door, excited, and keeping back so as
not to be seen by the people)
Chadbourne!
(The General joins him and they disappear)
66. Bishop Hardbrooke.
I sincerely hope
We're on the eve, however, of a day
When trouble-makers in the ranks of Labor,
Not only here in Foreston but elsewhere,
May find it to their interest to respect,
Nay, reverence as a thing ordained by God,
The right of men to earn their daily bread,
As well as profitable to obey the laws
Without the unseemly presence of armed men.
(There is a clapping of hands. General Chadbourne
appears just inside the door and beckons to Ardsley,
who goes in to him)
Bishop Hardbrooke.
And I will take occasion here and now
To say what you've been thinking all this while,
And in the presence of the man himself:
We are fortunate, my friends——
Ralph Ardsley.
(Appears and calls to one of the guests farther back)
The Governor.
Bishop Hardbrooke.
In having at the helm of our great State
One who loves order more than he loves votes.
(General clapping of hands)
Several.
Good!
67. Guest.
(In a low voice over the crowd)
Governor!
Several.
That's good!
(The Governor bows)
Cries.
Speech! Speech!
Governor Braddock.
My friends,
I quite agree with the Bishop.
Several.
Ha, ha, ha!
Governor Braddock.
I don't mean in his estimate of me.
(More laughter. The Governor catches sight of the guest
beckoning to him)
Governor Braddock.
But here's my better half. You might ask her.
Pardon me till I see——
Ralph Ardsley.
68. (Calls urgently to the Bishop in a voice that is barely
heard)
Go on! Go on!
Bishop Hardbrooke.
Society, my friends, is like this house,
This mansion that we all so much admire.
(Ardsley stands impassive till the Governor has gone out
and the Bishop has again got the attention of the
people, then goes quickly into the side room)
Bishop Hardbrooke.
Imagine what a state of things we'd have
If every wooden fellow in these walls,
Not only here but in the mill upstairs,
Should lend his heart to tongues of discontent
Until his very tools became a burden.
A Voice.
Anarchy.
Bishop Hardbrooke.
Very true. Where would this be,
This beautiful thing that Colonel Egerton
Has built with so much labor and so much taste?
And out there in the world where we all dwell,
Where all of us have places in the walls,
Some working with their hands on farms, in mines;
Some building; some at forges; at machines
Weaving our garments; others more endowed
Loaned to us from the higher planes of being,
Men of the Over-Soul, inventors, dreamers,
69. Planners of longer railroads, bigger mills,
The great preparers for the finer souls
That build the dome, the finishers of things,
Prophets of God, musicians, artists, poets,
As we've all seen how Colonel Egerton
In his third story has his books and pictures—
Suppose a bitter wind of discontent
Should shake the great walls of this social order,
Set the first story men against the second,
The second against the third, until the mass,
Throwing their tools down on the world's great floor,
Should clamor up the dome for pens and brushes,
Shutting their eyes to the cold facts of life
That we climb up Life's ladder by degrees—
(His attention is attracted for a moment to a group of
men that has been collecting forward centre, evidently
concerned with whatever it is that is going on in the
side room)
Bishop Hardbrooke.
(Recovering himself quickly)
But I'm afraid, my friends——
Several.
Go on! Go on!
Bishop Hardbrooke.
I'm wasting good material for a sermon.
A Man's Voice.
Pearls before swine.
Bishop Hardbrooke.
70. I started to say brethren.
(Laughter)
A Lady.
(In the foreground)
Isn't he just too bright for anything!
Bishop Hardbrooke.
But now——
A Man.
(Joining the group)
What's up?
Bishop Hardbrooke.
To come home to the task
That brother Egerton lays upon our ears.
We have all of us read stories and seen things.
(Laughter)
A Voice.
But ghosts of trees?
(General laughter)
Bishop Hardbrooke.
That, I admit, is rare.
(Mrs. Egerton, who, since the ringing of the telephone
bell, has shown an increasing anxiety as to the
71. message that has come, unable longer to contain
herself, comes hurriedly forward through the people)
Bishop Hardbrooke.
Don't let us scare you, sister Egerton.
(Laughter. The people turn just in time to see Governor
Braddock, General Chadbourne, and Ralph Ardsley
with overcoats on and hats in their hands, stealing
across to get out forward right. Mrs. Egerton hurries
into the room from which they came)
Ralph Ardsley.
It's nothing.
(The three go out)
Voices.
What's the matter? What's the matter?
Pale Lady.
It's something terrible, I know it is.
Lady in Black.
We always have to pay for our good times.
(George Egerton and Gladys Egerton come quickly from
the conservatory and enter the side room)
Elderly Lady.
I shouldn't wonder if those horrid strikers
Were burning the mill.
Lady in Black.
72. Or may be some one's hurt.
Lady With the Conspicuous Coiffure.
Provoking, isn't it?
Fat Lady.
What would we better do?
Young Matron.
(Calling out)
Please tell us what's the trouble.
(A silence)
Pale Lady.
I shall faint.
Bishop Hardbrooke.
(Coming forward)
It has been suggested, friends, in view of this
Personal something that has happened here—
I don't know what it is, but we all know
In trouble how we like to be alone.
Later I'll call them up and for us all
Extend our sympathy when we know the cause.
(There is a movement of people departing)
Pink Lady.
I wonder who it is?
Fat Lady.
73. They've shut the door.
Lady With the Conspicuous Coiffure.
'Twas more like anger; didn't you see his face?
Lady in Black.
When everything was so, so beautiful!
(They vanish with the other guests. A minute or so later
the Butler enters, right rear, and walks as though
dazed through the empty hall)
A Maid.
(Appearing right rear)
Charlie!
Second Maid.
(Appears beside her)
What is it?
Butler.
(Without turning)
Trouble at the mill.
First Maid.
Charlie!
Butler.
That's all I know.
74. Second Maid.
A riot?
Gladys Egerton.
(Appearing forward left)
Gone!
Father, they've gone!
George Egerton.
(Comes in quickly)
Look in the rooms.
(Goes rear)
Gladys Egerton.
(Looks in the room forward right)
They've gone!
George Egerton.
(Calls into the conservatory)
Chester! Marjorie! Well, I'll be damned!
Gladys Egerton.
I hate him, O I hate him!
George Egerton.
That's what comes!
Gladys Egerton.
75. What will we ever do! Just think of it!
George Egerton.
(To the Butler)
Why do you stand that way?
(Comes to the door forward left)
O do shut up,
Mother.
(Donald Egerton comes in, putting on his overcoat)
Mrs. Egerton.
(Following him)
Remember, Donald, he's our son.
George Egerton.
Always defending him! You make me sick.
Mrs. Egerton.
You've always said you never in your life
Lost hold upon yourself.
Gladys Egerton.
No dance to-night.
Egerton.
(To the Butler)
Tell Jack to bring the car to the front door.
76. (The Butler goes out centre right)
George Egerton.
Wait, father, till I get my——
(Starts for the room forward left)
Mrs. Egerton.
If he's done it—
He has some reason, Donald. And you know
Jergens has never liked him.
(Harry Egerton comes in right rear, his hat and shoulders
covered with snow)
Mrs. Egerton.
Harry! Harry!
(She hurries to him and embraces him)
Harry Egerton.
Mother!
Mrs. Egerton.
My son!
Harry Egerton.
I'm sorry.
(George Egerton reappears)
Gladys Egerton.
I just hate you!
You selfish thing! See what you've done!
77. Harry Egerton.
I'm sorry.
George Egerton.
(With a sneer)
He's very sorry, sister.
Egerton.
A pretty son!
Harry Egerton.
I hadn't the least intention, father——
George Egerton.
Damn you!
Harry Egerton.
Who 'phoned it in?
Mrs. Egerton.
What is it you've done, Harry?
George Egerton.
(To the Butler and the Maids who have appeared at the
doors)
Get away from there!
Harry Egerton.
78. Father——
(Egerton Tosses His Overcoat Into the Side Room)
Mrs. Egerton.
Harry, is it true
You kept the men from going back to work?
Harry Egerton.
I wanted to have a talk with father first.
Egerton.
Um!
George Egerton.
(To his mother)
There!
Mrs. Egerton.
But hear him, Donald.
Harry Egerton.
All my life
I've wanted to say something to you, father;
Especially since I went to work. You once,
When I came home from college, you remember,
And hadn't made my mind up what to do,
What my life work should be——
Egerton.
A pretty son!
79. Harry Egerton.
We talked together and you said that now
Three things lay open to me, that I could choose
And that you'd back me up. First, there was Art.
And though you didn't say so, I could see
You'd have been glad if I had chosen that.
I had a talent for it, so you said,
And I could study with the best of them.
You'd set aside a hundred thousand dollars;
And I could finish up by travelling,
Seeing the beautiful buildings of the world;
That I could take my time, then settle down
And glorify my land: that's what you said.
Then there was Public Life. You'd start me in
By giving me the Courier. That, you said,
Would give me at once a standing among men
And training in political affairs.
And that if I made good you'd see to it
I had a seat in Congress, and in the end
That probably I'd be Governor of the State.
And then you paused. You didn't like the third.
Business, you said, was an unpleasant life.
'Twas all right as you'd used it, as a means,
But as an end—And then you used words, father,
That changed my life although you didn't know it—
'Business, my son, is war; needful at times,
But as a life,—you shook your head and sighed.
With that we ended it, for some one came
And I went out. Six years ago last June,
The seventh of June; I can't forget the day.
The sun was shining but a strange new light
Lay over everything. All of a sudden
It dawned upon my mind that I'd been reared
Inside a garden full of flowers and trees,
And only now had chanced upon the gate
80. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com