SlideShare a Scribd company logo
Node js Design Patterns Master best practices to
build modular and scalable server side web
applications 2nd Edition Casciaro download
https://textbookfull.com/product/node-js-design-patterns-master-
best-practices-to-build-modular-and-scalable-server-side-web-
applications-2nd-edition-casciaro/
Download more ebook from https://textbookfull.com
We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!
Node js web development server side development with
Node 10 made easy Fourth Edition. Edition David Herron
https://textbookfull.com/product/node-js-web-development-server-
side-development-with-node-10-made-easy-fourth-edition-edition-
david-herron/
Pro Express js Master Express js The Node js Framework
For Your Web Development Mardan Azat
https://textbookfull.com/product/pro-express-js-master-express-
js-the-node-js-framework-for-your-web-development-mardan-azat/
RESTful Web API Design with Node js 10 Learn to create
robust RESTful web services with Node js MongoDB and
Express js 3rd Edition English Edition Valentin
Bojinov
https://textbookfull.com/product/restful-web-api-design-with-
node-js-10-learn-to-create-robust-restful-web-services-with-node-
js-mongodb-and-express-js-3rd-edition-english-edition-valentin-
bojinov/
Learning Node js Development Learn the fundamentals of
Node js and deploy and test Node js applications on the
web 1st Edition Andrew Mead
https://textbookfull.com/product/learning-node-js-development-
learn-the-fundamentals-of-node-js-and-deploy-and-test-node-js-
applications-on-the-web-1st-edition-andrew-mead/
Django Design Patterns and Best Practices 2nd Edition
Arun Ravindran
https://textbookfull.com/product/django-design-patterns-and-best-
practices-2nd-edition-arun-ravindran/
Node js 8 the Right Way Practical Server Side
JavaScript That Scales 1st Edition Jim Wilson
https://textbookfull.com/product/node-js-8-the-right-way-
practical-server-side-javascript-that-scales-1st-edition-jim-
wilson/
Node js for Embedded Systems Using Web Technologies to
Build Connected Devices 1st Edition Patrick Mulder
https://textbookfull.com/product/node-js-for-embedded-systems-
using-web-technologies-to-build-connected-devices-1st-edition-
patrick-mulder/
Node js MongoDB and Angular Web Development The
definitive guide to using the MEAN stack to build web
applications Developer s Library 2nd Edition Brad
Dayley & Brendan Dayley & Caleb Dayley
https://textbookfull.com/product/node-js-mongodb-and-angular-web-
development-the-definitive-guide-to-using-the-mean-stack-to-
build-web-applications-developer-s-library-2nd-edition-brad-
dayley-brendan-dayley-caleb-dayley/
Ultimate Node.js for Cross-Platform App Development:
Learn to Build Robust, Scalable, and Performant Server-
Side JavaScript Applications with Node.js (English
Edition) Kumar
https://textbookfull.com/product/ultimate-node-js-for-cross-
platform-app-development-learn-to-build-robust-scalable-and-
performant-server-side-javascript-applications-with-node-js-
Node js Design Patterns Master best practices to build modular and scalable server side web applications 2nd Edition Casciaro
Table of Contents
Chapter 1: Welcome to the Node.js platform 1
The Node.js philosophy 1
Small core 2
Small modules 2
Small surface area 3
Simplicity and pragmatism 4
Introduction to Node 5 and ES2015 5
Arrow Function 5
Let and Const 7
Class syntax 8
Enhanced Object literals 9
Map and Set collections 11
WeakMap and WeakSet collections 13
Template Literals 13
The reactor pattern 14
I/O is slow 14
Blocking I/O 15
Non-blocking I/O 16
Event demultiplexing 17
The reactor pattern 19
The non-blocking I/O engine of Node.js – libuv 21
The recipe for Node.js 22
Summary 23
Chapter 2: Node.js Essential Patterns 25
The callback pattern 25
The continuation-passing style 26
Synchronous continuation-passing style 26
Asynchronous continuation-passing style 27
Non continuation-passing style callbacks 28
Synchronous or asynchronous? 29
An unpredictable function 29
Unleashing Zalgo 29
Using synchronous APIs 31
Deferred execution 32
Node.js callback conventions 33
[ ii ]
Callbacks come last 33
Error comes first 34
Propagating errors 34
Uncaught exceptions 35
The module system and its patterns 37
The revealing module pattern 37
Node.js modules explained 37
A homemade module loader 38
Defining a module 40
Defining globals 40
module.exports vs exports 40
Function require is synchronous 41
The resolving algorithm 42
The module cache 43
Cycles 44
Module definition patterns 45
Named exports 45
Exporting a function 46
Exporting a constructor 47
Exporting an instance 48
Modifying other modules or the global scope 49
The observer pattern 50
The EventEmitter 51
Create and use an EventEmitter 52
Propagating errors 53
Make any object observable 53
Synchronous and asynchronous events 55
EventEmitter vs Callbacks 56
Combine callbacks and EventEmitter 57
Summary 58
Chapter 3: Asynchronous Control Flow Patterns With Callbacks 59
The difficulties of asynchronous programming 59
Creating a simple web spider 60
The callback hell 62
Using plain JavaScript 63
Callback discipline 64
Applying the callback discipline 64
Sequential execution 67
Executing a known set of tasks in sequence 67
Sequential iteration 68
Web spider version 2 68
[ iii ]
Sequential crawling of links 69
The pattern 70
Parallel execution 71
Web spider version 3 74
The pattern 75
Fixing race conditions with concurrent tasks 76
Limited parallel execution 77
Limiting the concurrency 78
Globally limiting the concurrency 79
Queues to the rescue 80
Web spider version 4 81
The async library 82
Sequential execution 82
Sequential execution of a known set of tasks 83
Sequential iteration 85
Parallel execution 86
Limited parallel execution 86
Summary 88
Index 89
1
Welcome to the Node.js
platform
Some principles and design patterns literally define the Node.js platform and its ecosystem;
the most peculiar ones are probably its asynchronous nature and its programming style that
makes heavy use of callbacks. It's important that we first dive into these fundamental
principles and patterns, not only for writing correct code, but also to be able to take effective
design decisions when it comes to solving bigger and more complex problems.
Another aspect that characterizes Node.js is its philosophy. Approaching Node.js is in fact
way more than simply learning a new technology; it's also embracing a culture and a
community. We will see how this greatly influences the way we design our applications
and components, and the way they interact with those created by the community.
In addition to these aspects it's worth knowing that the latest versions of Node.js introduced
support for many of the features described by ES2015, which makes the language even
more expressive and enjoyable to use. It is important to embrace these new syntactical and
functional additions to the language to be able to produce more concise and readable code
and come up with alternative ways to implement the design patterns that we are going to
see throughout this book.
In this chapter, we will learn the following topics:
The Node.js philosophy, the “Node way”
Node 5 and ES2015
The reactor pattern: the mechanism at the heart of the Node.js asynchronous
architecture
Welcome to the Node.js platform
[ 2 ]
The Node.js philosophy
Every platform has its own philosophy-a set of principles and guidelines that are generally
accepted by the community, an ideology of doing things that influences the evolution of a
platform, and how applications are developed and designed. Some of these principles arise
from the technology itself, some of them are enabled by its ecosystem, some are just trends
in the community, and others are evolutions of different ideologies. In Node.js, some of
these principles come directly from its creator, Ryan Dahl, from all the people who
contributed to the core, from charismatic figures in the community, and some of the
principles are inherited from the JavaScript culture or are influenced by the Unix
philosophy.
None of these rules are imposed and they should always be applied with common sense;
however, they can prove to be tremendously useful when we are looking for a source of
inspiration while designing our programs.
You can find an extensive list of software development philosophies in
Wikipedia at
http://en.wikipedia.org/wiki/List_of_software_development
_philosophies
Small core
The Node.js core itself has its foundations built on a few principles; one of these is, having
the smallest set of functionality, leaving the rest to the so-called userland (or userspace),the
ecosystem of modules living outside the core. This principle has an enormous impact on the
Node.js culture, as it gives freedom to the community to experiment and iterate fast on a
broader set of solutions within the scope of the userland modules, instead of being imposed
with one slowly evolving solution that is built into the more tightly controlled and stable
core. Keeping the core set of functionality to the bare minimum then, not only becomes
convenient in terms of maintainability, but also in terms of the positive cultural impact that
it brings on the evolution of the entire ecosystem.
Small modules
Node.js uses the concept of module as a fundamental mean to structure the code of a
program. It is the brick for creating applications and reusable libraries called packages (a
package is also frequently referred to as just module; since, usually it has one single module
as an entry point). In Node.js, one of the most evangelized principles is to design small
modules, not only in terms of code size, but most importantly in terms of scope.
Welcome to the Node.js platform
[ 3 ]
This principle has its roots in the Unix philosophy, particularly in two of its precepts, which
are as follows:
“Small is beautiful.”
“Make each program do one thing well.”
Node.js brought these concepts to a whole new level. Along with the help of npm, the
official package manager, Node.js helps solving the dependency hell problem by making sure
that each installed package will have its own separate set of dependencies, thus enabling a
program to depend on a lot of packages without incurring in conflicts. The Node way, in
fact, involves extreme levels of reusability, whereby applications are composed of a
highnumber of small, well-focused dependencies. While this can be considered unpractical
or even totally unfeasible in other platforms, in Node.js this practice is encouraged. As a
consequence, it is not rare to find npm packages containing less than 100 lines of code or
exposing only one single function.
Besides the clear advantage in terms of reusability, a small module is also considered to be
the following:
Easier to understand and use
Simpler to test and maintain
Perfect to share with the browser
Having smaller and more focused modules empowers everyone to share or reuse even the
smallest piece of code; it's the Don't Repeat Yourself (DRY) principle applied at a whole
new level.
Small surface area
In addition to being small in size and scope, Node.js modules usually also have the
characteristic of exposing only a minimal set of functionality. The main advantage here is an
increased usability of the API, which means that the API becomes clearer to use and is less
exposed to erroneous usage. Most of the time, in fact, the user of a component is interested
only in a very limited and focused set of features, without the need to extend its
functionality or tap into more advanced aspects.
In Node.js, a very common pattern for defining modules is to expose only one piece of
functionality, such as a function or a constructor, while letting more advanced aspects or
secondary features become properties of the exported function or constructor. This helps
the user to identify what is important and what is secondary. It is not rare to find modules
that expose only one function and nothing else, for the simple fact that it provides a single,
Welcome to the Node.js platform
[ 4 ]
unmistakably clear entry point.
Another characteristic of many Node.js modules is the fact that they are created to be used
rather than extended. Locking down the internals of a module by forbidding any possibility
of an extension might sound inflexible, but it actually has the advantage of reducing the use
cases, simplifying its implementation, facilitating its maintenance, and increasing its
usability.
Simplicity and pragmatism
Have you ever heard of the Keep It Simple, Stupid (KISS) principle? Or the famous quote:
“Simplicity is the ultimate sophistication.”
– Leonardo da Vinci
Richard P. Gabriel, a prominent computer scientist coined the term worse is better to describe
the model, whereby less and simpler functionality is a good design choice for software. In
his essay,The rise of worse is better, he says:
“The design must be simple, both in implementation and interface. It is more important for
the implementation to be simple than the interface. Simplicity is the most important
consideration in a design.”
Designing a simple, as opposed to a perfect, feature-full software, is a good practice for
several reasons: it takes less effort to implement, allows faster shipping with less resources,
is easier to adapt, and is easier to maintain and understand. These factors foster the
community contributions and allow the software itself to grow and improve.
In Node.js, this principle is also enabled by JavaScript, which is a very pragmatic language.
It's not rare, in fact, to see simple functions, closures, and object literals replacing complex
class hierarchies. Pure object-oriented designs often try to replicate the real world using the
mathematical terms of a computer system without considering the imperfection and the
complexity of the real world itself. The truth is that our software is always an
approximation of the reality and we would probably have more success in trying to get
something working sooner and with reasonable complexity, instead of trying to create a
near-perfect software with a huge effort and tons of code to maintain.
Throughout this book, we will see this principle in action many times. For example, a
considerable number of traditional design patterns, such as Singleton or Decorator can have
a trivial, even if sometimes not foolproof implementation and we will see how an
uncomplicated, practical approach most of the time is preferred to a pure, flawless design.
Welcome to the Node.js platform
[ 5 ]
Introduction to Node 5 and ES2015
At the time of writing the most recent major versions of Node.js (Node 4 and Node 5) come
with a great addition to the language: a wide support for many of the new features
introduced in the ECMAScript 2015 specification (in short ES2015 and formerly known also
as ES6) which aims to make the language even more flexible and enjoyable.
Throughout this book, we will widely adopt some of these new features in the code
examples. These concepts are still fresh within the Node.js community so it's worth having
a quick look at the most important ES2015 specific features currently supported in Node.js.
Our version of reference is Node 5, more specifically version 5.1.
Many of these features will work correctly only when the strict mode is enabled. Strict
mode can be easily enabled by adding ause strict; statement at the very beginning of
your script. For the sake of brevity, we will not write this line in our code examples but you
should remember to add it to be able to run them correctly.
The following list is not meant to be exhaustive but just an introduction to the ES2015
features supported in Node, so that you can easily understand all the code examples in the
rest of this book.
Arrow Function
One of the most appreciated features introduced by ES2015 is the support for arrow
functions. Arrow function is a more concise syntax for defining functions, especially useful
when defining a callback. To better understand the advantages of this syntax let's see first
an example of a classic filtering on an array:
var numbers = [2, 6, 7, 8, 1];
var even = numbers.filter(function(x) {
return x%2 === 0;
});
This code above can be rewritten as follows using the arrow function syntax:
var numbers = [2, 6, 7, 8, 1];
var even = numbers.filter((x) => x%2 === 0);
The filter function can be defined inline, the keyword function is removed, leaving only
the list of parameters, which is followed by => (the arrow), which in turn is followed by the
body of the function. When the body of the function is just one line there's no need to write
the return keyword as it is applied implicitly. If we need to add more lines of code to the
body of the function, we can wrap them in curly brackets, but beware that in this case the
Welcome to the Node.js platform
[ 6 ]
return is not automatically implied, so it needs to be stated explicitly, as in the following
example:
var numbers = [2, 6, 7, 8, 1];
var even = numbers.filter((x) => {
if (x%2 === 0) {
console.log(x + ' is even!');
return true;
}
});
But there is another important feature to know about arrow functions: arrow functions are
bound to their lexical scope. This means that inside an arrow function the value of this is
the same as in the parent block. Let's clarify this concept with an example:
function DelayedGreeter(name) {
this.name = name;
}
DelayedGreeter.prototype.greet = function() {
setTimeout( function cb() {
console.log('Hello ' + this.name);
}, 500);
};
let greeter = new DelayedGreeter('World');
greeter.greet(); // will print "Hello undefined"
In this code we are defining a simple “greeter” prototype which accepts a name as
argument. Then we are adding the greet method to the prototype. This function is
supposed to print “Hello” and the name defined in the current instance after 500
milliseconds it has been called. But this function is broken because inside the timeout
callback function (cb), the scope of the function is different from the scope of the greet
method and the value of this is undefined.
Before Node.js introduced support for arrow functions, to fix this we needed to change the
greet function using bind as follows:
DelayedGreeter.prototype.greet = function() {
setTimeout( (function cb() {
console.log('Hello ' + this.name);
}).bind(this), 500);
};
But since we have now arrow functions and since they are bound to their lexical scope, we
can just use an arrow function as callback to solve the issue:
Welcome to the Node.js platform
[ 7 ]
DelayedGreeter.prototype.greet = function() {
setTimeout( () => console.log('Hello ' + this.name), 500);
};
This is a very handy feature, most of the time it makes our code more concise and
straightforward.
Let and Const
Historically JavaScript offered only function scope and global scope to control the lifetime
and the visibility of a variable. For instance if you declare a variable inside the body of an if
statement the variable will be accessible even outside the statement, whether or not the
body of the statement has been executed. Let's see it more clearly with an example:
if (false) {
var x = "hello";
}
console.log(x);
This code will not fail as we might expect and it will just print undefined in the console.
This behavior has been cause of many bugs and frustration and that is the reason why
ES2015 introduces the let keyword to declare variables that respect the block scope. Let's
replace var with let in our previous example:
if (false) {
let x = "hello";
}
console.log(x);
This code will raise a ReferenceError: x is not defined because we are trying to
print a variable that has been defined inside another block scope.
To give a more meaningful example we can use the let keyword to define a temporary
variable to be used as an index for a loop:
for (let i=0; i < 10; i++) {
// do something here
}
console.log(i);
As in the previous example, this code will raise a ReferenceError: i is not defined
error.
This protective behavior introduced with let allows us to write safer code, because if we
accidentally access variables that belong to another scope we will get an error that will
Welcome to the Node.js platform
[ 8 ]
allow us to easily spot the bug and avoid potentially dangerous side effects.
ES2015 introduces also the const keyword. This keyword allows to declare read-only
variables. Let's see a quick example:
const x = 'This will never change';
x = '...';
This code will raise a “TypeError: Assignment to constant variable” error because
we are trying to change the value of a constant.
Constants are extremely useful when you want to protect a value from being accidentally
changed in your code.
Class syntax
ES2015 introduces a new syntax to leverage prototypical inheritance in a way that should
sound more familiar to all the developers that come from classic object oriented languages
such as Java or C#. It's important to underline that this new syntax does not change the way
objects are managed internally by the JavaScript runtime, they still inherits properties and
functions through prototypes and not through classes. While this new alternative syntax
can be very handy and readable, as a developer is important to understand that it is just a
syntactic sugar.
Let's see how it works with a trivial example. First of all, let's describe a Person using the
classic prototype based approach:
function Person(name, surname, age) {
this.name = name;
this.surname = surname;
this.age = age;
}
Person.prototype.getFullName = function() {
return this.name + ' ' + this.surname;
}
Person.older = function(person1, person2) {
return (person1.age >= person2.age) ? person1 : person2;
}
As you can see a person has a name, a surname and an age. We are providing to our
prototype a helper function that allows us to easily get the full name of a person object and
a generic helper function accessible directly from the Person prototype that returns the
Welcome to the Node.js platform
[ 9 ]
older person between two Person instances given as input.
Let's see now how we can implement the same example using the new handy ES2015 class
syntax:
class Person {
constructor (name, surname, age) {
this.name = name;
this.surname = surname;
this.age = age;
}
getFullName () {
return this.name + ' ' + this.surname;
}
static older (person1, person2) {
return (person1.age >= person2.age) ? person1 : person2;
}
}
This syntax results more readable and straightforward to understand. We are explicitly
stating what is the constructor for the class and declaring the function older as a static
method.
Both implementations are completely interchangeable, but the real killer feature of the new
syntax is the possibility of extending the Person prototype using the extend and the
super keywords. Let's assume we want to create the PersonWithMiddlename class:
class PersonWithMiddlename extends Person {
constructor (name, middlename, surname, age) {
super(name, surname, age);
this.middlename = middlename;
}
getFullName () {
return this.name + ' ' + this.middlename + ' ' + this.surname;
}
}
What is worth noticing in this second example is that the syntax really resembles what is
common in other object oriented languages. We are declaring the class from which we want
to extend, we define a new constructor that can call the parent one using the keyword
super and we override the getFullName method to add support for our middle name.
Welcome to the Node.js platform
[ 10 ]
Enhanced Object literals
As long with the new class syntax, ES2015 introduced an enhanced object literals syntax.
This syntax offers a shorthand to assign variables and functions as members of the object,
allows to define computed member names at creation time and also handy setters and
getters methods.
Let's make all of this clear with some examples:
let x = 22;
let y = 17;
let obj = { x, y };
obj will be an object containing the keys x and y, respectively with the values 22 and 17.
We can do the same thing with functions:
module.exports = {
square (x) {
return x * x;
},
cube (x) {
return x * x * x;
}
};
In this case we are writing a module that exports the functions square and cube mapped to
properties with the same name. Notice that we don't need to specify the keyword
function.
Let's see in another example how we can use computed property names:
let namespace = '-webkit-';
let style = {
[namespace + 'box-sizing'] : 'border-box',
[namespace + 'box-shadow'] : '10px 10px 5px #888888'
};
In this case the resulting object will contain the properties -webkit-box-sizing and -
webkit-box-shadow.
Let's see now how we can use the new setter and getter syntax by jumping directly to an
example:
let person = {
name : 'George',
surname : 'Boole',
Welcome to the Node.js platform
[ 11 ]
get fullname () {
return this.name + ' ' + this.surname;
},
set fullname (fullname) {
let parts = fullname.split(' ');
this.name = parts[0];
this.surname = parts[1];
}
}
console.log(person.fullname); // "George Boole"
console.log(person.fullname = 'Alan Turing'); // "Alan Turing"
console.log(person.name); // "Alan"
In this example we are defining three properties, two normal name and surname and a
computed property fullname through the set and get syntax. As you can see from the
result of the console.log calls, we can access the computed property as if it was a regular
property inside the object for both reading and writing the value. It's worth noticing that the
second call to console.log prints “Alan Turing”. This happens because by default every
set function returns the value that is returned by the get function for the same property, in
this case get fullname.
Map and Set collections
As JavaScript developers we are used to create hash maps using plain objects. ES2015
introduces a new prototype called Map that is specifically designed to leverage hash map
collections in a more secure, flexible and intuitive way. Let's see a quick example:
let profiles = new Map();
profiles.set('twitter', '@adalovelace');
profiles.set('facebook', 'adalovelace');
profiles.set('googleplus', 'ada');
profiles.size; // 3
profiles.has('twitter'); // true
profiles.get('twitter'); // "@adalovelace"
profiles.has('youtube'); // false
profiles.delete('facebook');
profiles.has('facebook'); // false
profiles.get('facebook'); // undefined
for (let entry of profiles) {
console.log(entry);
}
Welcome to the Node.js platform
[ 12 ]
As you can see the Map prototype offers several handy methods like set, get, has and
delete and the size attribute. We can also iterate through all the entries using the for
... of syntax. Every entry in the loop will be an array containing the key as first element
and the value as second element. This interface is very intuitive and self-explanatory.
But what makes maps really interesting is the possibility of using functions and objects as
keys of the map and this was something that is not entirely possible using plain objects,
because with objects all the keys are automatically casted to strings. This opens new
opportunities, for example we can build a micro testing framework leveraging this feature:
let tests = new Map();
tests.set(() => 2+2, 4);
tests.set(() => 2*2, 4);
tests.set(() => 2/2, 1);
for (let entry of tests) {
console.log((entry[0]() === entry[1]) ? ' ' : ' ');
}
As you can see in this last example, we are storing functions as keys and expected results as
values. Then we can iterate through our hash map and execute all the functions. It's also
worth noticing that when we iterate through the map all the entries respect the order in
which they have been inserted, this is also something that was not always guaranteed with
plain objects.
Along with Map, ES2015 also introduces the Set prototype. This prototype allows us to
easily construct sets, which means lists with unique values.
let s = new Set([0, 1, 2, 3]);
s.add(3); // will not be added
s.size; // 4
s.delete(0);
s.has(0); // false
for (let entry of s) {
console.log(entry);
}
As you can see in this example the interface is quite similar to the one we have just seen for
Welcome to the Node.js platform
[ 13 ]
Map. We have the methods add (instead of set), has and delete and the property size.
We can also iterate through the set and in this case every entry is a value, in our example it
will be one of the numbers in the set. Finally, sets can also contain objects and functions as
values.
WeakMap and WeakSet collections
ES2015 defines also a weak version of the Map and the Set prototypes called WeakMap and
WeakSet.
WeakMap is quite similar to Map in terms of interface, there are only two main differences:
there is no way to iterate all over the entries and it allows to have only objects as keys.
While this might seem as a limitation there is a good reason behind it, in fact the distinctive
feature of WeakMap is that it allows objects used as keys to be garbage collected when the
only reference left is inside a WeakMap. This is extremely useful when we are storing some
metadata associated to an object that might get deleted during the regular lifetime of the
application. Let's see an example:
let obj = {};
let map = new WeakMap();
map.set(obj, {metadata: "some_metadata"});
console.log(map.get(obj)); // {metadata: "some_metadata"}
obj = undefined; // now obj and metadata will be cleaned up in the next gc
cycle
In this code we are creating a plain object called obj. Then we store some metadata for this
object in a new WeakMap called map. We can access this metadata with the map.get method.
Later, when we cleanup the object by assigning its variable to undefined, the object will be
correctly garbage collected and its metadata removed from the map.
Similarly, to WeakMap, WeakSet is the weak version of Set: it exposes the same interface of
Set but it allows to store only objects and cannot be iterated. Again the difference with Set
is that WeakSet allows objects to be garbage collected when their only reference left is in the
weak set.
It's important to understand that WeakMap and WeakSet are not better or worse than Map
and Set, they are simply more suitable for different use cases.
Template Literals
ES2015 offers a new alternative and more powerful syntax to define strings: the template
Welcome to the Node.js platform
[ 14 ]
literals. This syntax uses back ticks (`) as delimiters and offers several benefits compared to
regular quoted (') or double-quoted (") delimited strings. The main ones are that template
literals syntax can interpolate variables or expressions using ${expression} inside the string
(this is the reason why this syntax is called “template”) and that strings can finally be
multiline. Let's see a quick example:
let name = "Leonardo";
let interests = ["arts", "architecture", "science", "music",
"mathematics"];
let birth = { year : 1452, place : 'Florence' };
let text = `${name} was an Italian polymath interested in many topics such
as ${interests.join(', ')}.
He was born in ${birth.year} in ${birth.place}.`;
console.log(text);
This code will print:
Leonardo was an Italian polymath interested in many topics such
as arts, architecture, science, music, mathematics.
He was born in 1452 in Florence.
A more extended and up to date list of all the supported ES2015 features is
available in the official Node.js documentation:
https://nodejs.org/en/docs/es6/
The reactor pattern
In this section, we will analyze the reactor pattern, which is the heart of the Node.js
asynchronous nature. We will go through the main concepts behind the pattern, such as the
single-threaded architecture and the non-blocking I/O, and we will see how this creates the
foundation for the entire Node.js platform.
I/O is slow
I/O is definitely the slowest among the fundamental operations of a computer. Accessing
the RAM is in the order of nanoseconds (10e
-9
seconds), while accessing data on the disk or
the network is in the order of milliseconds (10e-3 seconds). For the bandwidth, it is the same
story; RAM has a transfer rate consistently in the order of GB/s, while disk and network
varies from MB/s to, optimistically, GB/s. I/O is usually not expensive in terms of CPU,
but it adds a delay between the moment the request is sent and the moment the operation
completes. On top of that, we also have to consider thehuman factor; often, the input of an
Welcome to the Node.js platform
[ 15 ]
application comes from a real person, for example, the click of a button or a message sent in
a real-time chat application, so the speed and frequency of I/O don't depend only on
technical aspects, and they can be many orders of magnitude slower than the disk or
network.
Blocking I/O
In traditional blocking I/O programming, the function call corresponding to an I/O request
will block the execution of the thread until the operation completes. This can go from a few
milliseconds, in case of a disk access, to minutes or even more, in case the data is generated
from user actions, such as pressing a key. The following pseudocode shows a typical
blocking read performed against a socket:
//blocks the thread until the data is available
data = socket.read();
//data is available
print(data);
It is trivial to notice that a web server that is implemented using blocking I/O will not be
able to handle multiple connections in the same thread; each I/O operation on a socket will
block the processing of any other connection. For this reason, the traditional approach to
handle concurrency in web servers is to kick off a thread or a process (or to reuse one taken
from a pool) for each concurrent connection that needs to be handled. This way, when a
thread gets blocked for an I/O operation it will not impact the availability of the other
requests, because they are handled in separate threads.
The following image illustrates this scenario:
Welcome to the Node.js platform
[ 16 ]
The preceding image lays emphasis on the amount of time each thread is idle, waiting for
new data to be received from the associated connection. Now, if we also consider that any
type of I/O can possibly block a request, for example, while interacting with databases or
with the filesystem, we soon realize how many times a thread has to block in order to wait
for the result of an I/O operation. Unfortunately, a thread is not cheap in terms of system
resources, it consumes memory and causes context switches, so having a long running
thread for each connection and not using it for most of the time, is not the best compromise
in terms of efficiency.
Non-blocking I/O
In addition to blocking I/O, most modern operating systems support another mechanism to
access resources, called non-blocking I/O. In this operating mode, the system call always
returns immediately without waiting for the data to be read or written. If no results are
available at the moment of the call, the function will simply return a predefined constant,
indicating that there is no data available to return at that moment.
For example, in Unix operating systems, the fcntl() function is used to manipulate an
existing file descriptor to change its operating mode to non-blocking (with the O_NONBLOCK
flag). Once the resource is in non-blocking mode, any read operation will fail with a return
code, EAGAIN, in case the resource doesn't have any data ready to be read.
The most basic pattern for accessing this kind of non-blocking I/O is to actively poll the
resource within a loop until some actual data is returned; this is called busy-waiting. The
following pseudocode shows you how it's possible to read from multiple resources using
Welcome to the Node.js platform
[ 17 ]
non-blocking I/O and a polling loop:
resources = [socketA, socketB, pipeA];
while(!resources.isEmpty()) {
for(i = 0; i < resources.length; i++) {
resource = resources[i];
//try to read
var data = resource.read();
if(data === NO_DATA_AVAILABLE)
//there is no data to read at the moment
continue;
if(data === RESOURCE_CLOSED)
//the resource was closed, remove it from the list
resources.remove(i);
else
//some data was received, process it
consumeData(data);
}
}
You can see that, with this simple technique, it is already possible to handle different
resources in the same thread, but it's still not efficient. In fact, in the preceding example, the
loop will consume precious CPU only for iterating over resources that are unavailable most
of the time. Polling algorithms usually result in a huge amount of wasted CPU time.
Event demultiplexing
Busy-waiting is definitely not an ideal technique for processing non-blocking resources, but
luckily, most modern operating systems provide a native mechanism to handle concurrent,
non-blocking resources in an efficient way; this mechanism is called synchronous event
demultiplexer or event notification interface. This component collects and queues I/O
events that come from a set of watched resources, and block until new events are available
to process. The following is the pseudocode of an algorithm that uses a generic synchronous
event demultiplexer to read from two different resources:
socketA, pipeB;
watchedList.add(socketA, FOR_READ); //[1]
watchedList.add(pipeB, FOR_READ);
while(events = demultiplexer.watch(watchedList)) { //[2]
//event loop
foreach(event in events) { //[3]
//This read will never block and will always return data
data = event.resource.read();
if(data === RESOURCE_CLOSED)
//the resource was closed, remove it from the watched list
Welcome to the Node.js platform
[ 18 ]
demultiplexer.unwatch(event.resource);
else
//some actual data was received, process it
consumeData(data);
}
}
These are the important steps of the preceding pseudocode:
The resources are added to a data structure, associating each one of them with a
1.
specific operation, in our example a read.
The event notifier is set up with the group of resources to be watched. This call is
2.
synchronous and blocks until any of the watched resources is ready for a read.
When this occurs, the event demultiplexer returns from the call and a new set of
events is available to be processed.
Each event returned by the event demultiplexer is processed. At this point, the
3.
resource associated with each event is guaranteed to be ready to read and to not
block during the operation. When all the events are processed, the flow will block
again on the event demultiplexer until new events are again available to be
processed. This is called the event loop.
It's interesting to see that with this pattern, we can now handle several I/O operations
inside a single thread, without using a busy-waiting technique. The following image shows
us how a web server would be able to handle multiple connections using a synchronous
event demultiplexer and a single thread:
The previous image helps us understand how concurrency works in a single-threaded
application using a synchronous event demultiplexer and non-blocking I/O. We can see
Welcome to the Node.js platform
[ 19 ]
that using only one thread does not impair our ability to run multiple I/O bound tasks
concurrently. The tasks are spread over time, instead of being spread across multiple
threads. This has the clear advantage of minimizing the total idle time of the thread, as
clearly shown in the image. This is not the only reason for choosing this model. To have
only a single thread, in fact, also has a beneficial impact on the way programmers approach
concurrency in general. Throughout the book, we will see how the absence of in-process
race conditions and multiple threads to synchronize, allows us to use much simpler
concurrency strategies.
In the next chapter, we will have the opportunity to talk more about the concurrency model
of Node.js.
The reactor pattern
We can now introduce the reactor pattern, which is a specialization of the algorithms
presented in the previous section. The main idea behind it is to have a handler (which in
Node.js is represented by a callback function) associated with each I/O operation, which
will be invoked as soon as an event is produced and processed by the event loop. The
structure of the reactor pattern is shown in the following image:
Welcome to the Node.js platform
[ 20 ]
This is what happens in an application using the reactor pattern:
The application generates a new I/O operation by submitting a request to the
1.
Event Demultiplexer. The application also specifies a handler, which will be
invoked when the operation completes. Submitting a new request to the Event
Demultiplexer is a non-blocking call and it immediately returns the control back
to the application.
When a set of I/O operations completes, the Event Demultiplexer pushes the new
2.
events into the Event Queue.
At this point, the Event Loop iterates over the items of the Event Queue.
3.
For each event, the associated handler is invoked.
4.
The handler, which is part of the application code, will give back the control to
5.
the Event Loop when its execution completes (5a). However, new asynchronous
operations might be requested during the execution of the handler (5b), causing
Welcome to the Node.js platform
[ 21 ]
new operations to be inserted in the Event Demultiplexer (1), before the control is
given back to the Event Loop.
When all the items in the Event Queue are processed, the loop will block again on
6.
the Event Demultiplexer which will then trigger another cycle.
The asynchronous behavior is now clear: the application expresses the interest to access a
resource at one point in time (without blocking) and provides a handler, which will then be
invoked at another point in time when the operation completes.
A Node.js application will exit automatically when there are no more
pending operations in the Event Demultiplexer, and no more events to be
processed inside the Event Queue.
We can now define the pattern at the heart of Node.js.
Pattern (reactor): handles I/O by blocking until new events are available from a set of
observed resources, and then reacting by dispatching each event to an associated handler.
The non-blocking I/O engine of Node.js – libuv
Each operating system has its own interface for the Event Demultiplexer: epoll on Linux,
kqueue on Mac OS X, andI/O Completion Port API (IOCP) on Windows. Besides that, each
I/O operation can behave quite differently depending on the type of the resource, even
within the same OS. For example, in Unix, regular filesystem files do not support non-
blocking operations, so, in order to simulate a non-blocking behavior, it is necessary to use a
separate thread outside the Event Loop. All these inconsistencies across and within the
different operating systems required a higher-level abstraction to be built for the Event
Demultiplexer. This is exactly why the Node.js core team created a C library called libuv,
with the objective to make Node.js compatible with all the major platforms and normalized
the non-blocking behavior of the different types of resource; libuv today represents the
low-level I/O engine of Node.js.
Besides abstracting the underlying system calls, libuv also implements the reactor pattern,
thus providing an API for creating event loops, managing the event queue, running
asynchronous I/O operations, and queuing other types of tasks.
A great resource to learn more about libuv is the free online book created
by Nikhil Marathe, which is available at
http://nikhilm.github.io/uvbook/
Welcome to the Node.js platform
[ 22 ]
The recipe for Node.js
The reactor pattern and libuv are the basic building blocks of Node.js, but we need the
following three other components to build the full platform:
A set of bindings responsible for wrapping and exposing libuv and other low-
level functionality to JavaScript.
V8, the JavaScript engine originally developed by Google for the Chrome
browser. This is one of the reasons why Node.js is so fast and efficient. V8 is
acclaimed for its revolutionary design, its speed, and for its efficient memory
management.
A core JavaScript library (called node-core) thatimplements the high-level
Node.js API.
Finally, this is the recipe of Node.js, and the following image represents its final
architecture:
Welcome to the Node.js platform
[ 23 ]
Summary
In this chapter, we have seen how the Node.js platform is based on a few important
principles that provide the foundation to build efficient and reusable code. The philosophy
and the design choices behind the platform have, in fact, a strong influence on the structure
and behavior of every application and module we create. Often, for a developer moving
from another technology, these principles might seem unfamiliar and the usual instinctive
Welcome to the Node.js platform
[ 24 ]
reaction is to fight the change by trying to find more familiar patterns inside a world which
in reality requires a real shift in the mindset.
On one hand, the asynchronous nature of the reactor pattern requires a different
programming style made of callbacks and things that happen at a later time, without
worrying too much about threads and race conditions. On the other hand, the module
pattern and its principles of simplicity and minimalism creates interesting new scenarios in
terms of reusability, maintenance, and usability.
Finally, besides the obvious technical advantages of being fast, efficient, and based on
JavaScript, Node.js is attracting so much interest because of the principles we have just
discovered. For many, grasping the essence of this world feels like returning to the origins,
to a more humane way of programming for both size and complexity and that's why
developers end up falling in love with Node.js. The introduction of ES2015 makes things
even more interesting and open new scenarios for being able to embrace all these
advantages with an even more expressive syntax.
In the next chapter, we will get into deep of the two basic asynchronous patterns used in
Node.js: the callback pattern and the event emitter. We will also understand the difference
between synchronous and asynchronous code and how to avoid to write unpredictable
functions.
2
Node.js Essential Patterns
Embracing the asynchronous nature of Node.js is not trivial at all, especially if coming from
a language such as PHP where it is not usual to deal with asynchronous code.
With synchronous programming we are used to imagine code as a series of consecutive
computing steps defined to solve a specific problem. Every operation is blocking which
means that only when an operation is completed it is possible to execute the next one. This
approach makes the code easy to understand and debug.
Instead, in asynchronous programming some operations like reading a file or performing a
network request can be executed asynchronously in the background. When an
asynchronous operation is performed, the next one is executed immediately, even if the
previous (asynchronous) operation has not finished yet. The operations pending on the
background can complete at any time and the whole application should be programmed to
react in the proper way when an asynchronous finishes.
While this non-blocking approach can guarantee superior performances compared to an
always-blocking scenario, it provides a paradigm that is hard to picture in mind and that
can get really cumbersome when dealing with more advanced applications that requires
complex control flows.
Node.js offers a series of tools and design patterns to deal optimally with asynchronous
code and it's important to learn how to use them to gain confidence with asynchronous
coding and write applications that are both performant and easy to understand and debug.
In this chapter, we will see two of the most important asynchronous patterns: callback and
event emitter.
The callback pattern
Random documents with unrelated
content Scribd suggests to you:
As mademoiselle de la Mole obstinately refused to look at him,
Julien on the third day in spite of her evident objection, followed her
into the billiard-room after dinner.
“Well, sir, you think you have acquired some very strong rights
over me?” she said to him with scarcely controlled anger, “since you
venture to speak to me, in spite of my very clearly manifested wish?
Do you know that no one in the world has had such effrontery?”
The dialogue of these two lovers was incomparably humourous.
Without suspecting it, they were animated by mutual sentiments of
the most vivid hate. As neither the one nor the other had a meekly
patient character, while they were both disciples of good form, they
soon came to informing each other quite clearly that they would
break for ever.
“I swear eternal secrecy to you,” said Julien. “I should like to add
that I would never address a single word to you, were it not that a
marked change might perhaps jeopardise your reputation.” He
saluted respectfully and left.
He accomplished easily enough what he believed to be a duty; he
was very far from thinking himself much in love with mademoiselle
de la Mole. He had certainly not loved her three days before, when
he had been hidden in the big mahogany cupboard. But the moment
that he found himself estranged from her for ever his mood
underwent a complete and rapid change.
His memory tortured him by going over the least details in that
night, which had as a matter of fact left him so cold. In the very
night that followed this announcement of a final rupture, Julien
almost went mad at being obliged to own to himself that he loved
mademoiselle de la Mole.
This discovery was followed by awful struggles: all his emotions
were overwhelmed.
Two days later, instead of being haughty towards M. de Croisenois,
he could have almost burst out into tears and embraced him.
His habituation to unhappiness gave him a gleam of
commonsense, he decided to leave for Languedoc, packed his trunk
and went to the post.
He felt he would faint, when on arriving at the office of the mails,
he was told that by a singular chance there was a place in the
Toulouse mail. He booked it and returned to the Hôtel de la Mole to
announce his departure to the marquis.
M. de la Mole had gone out. More dead than alive Julien went into
the library to wait for him. What was his emotion when he found
mademoiselle de la Mole there.
As she saw him come, she assumed a malicious expression which
it was impossible to mistake.
In his unhappiness and surprise Julien lost his head and was weak
enough to say to her in a tone of the most heartfelt tenderness. “So
you love me no more.”
“I am horrified at having given myself to the first man who came
along,” said Mathilde crying with rage against herself.
“The first man who came along,” cried Julien, and he made for an
old mediæval sword which was kept in the library as a curiosity.
His grief—which he thought was at its maximum at the moment
when he had spoken to mademoiselle de la Mole—had been
rendered a hundred times more intense by the tears of shame which
he saw her shedding.
He would have been the happiest of men if he had been able to
kill her.
When he was on the point of drawing the sword with some
difficulty from its ancient scabbard, Mathilde, rendered happy by so
novel a sensation, advanced proudly towards him, her tears were
dry.
The thought of his benefactor—the marquis de la Mole—presented
itself vividly to Julien. “Shall I kill his daughter?” he said to himself,
“how horrible.” He made a movement to throw down the sword.
“She will certainly,” he thought, “burst out laughing at the sight of
such a melodramatic pose:” that idea was responsible for his
regaining all his self-possession. He looked curiously at the blade of
the old sword as though he had been looking for some spot of rust,
then put it back in the scabbard and replaced it with the utmost
tranquillity on the gilt bronze nail from which it hung.
The whole manœuvre, which towards the end was very slow,
lasted quite a minute; mademoiselle de la Mole looked at him in
astonishment. “So I have been on the verge of being killed by my
lover,” she said to herself.
This idea transported her into the palmiest days of the age of
Charles IX. and of Henri III.
She stood motionless before Julien, who had just replaced the
sword; she looked at him with eyes whose hatred had disappeared.
It must be owned that she was very fascinating at this moment,
certainly no woman looked less like a Parisian doll (this expression
symbolised Julien’s great objection to the women of this city).
“I shall relapse into some weakness for him,” thought Mathilde; “it
is quite likely that he will think himself my lord and master after a
relapse like that at the very moment that I have been talking to him
so firmly.” She ran away.
“By heaven, she is pretty said Julien as he watched her run and
that’s the creature who threw herself into my arms with so much
passion scarcely a week ago ... and to think that those moments will
never come back? And that it’s my fault, to think of my being lacking
in appreciation at the very moment when I was doing something so
extraordinarily interesting! I must own that I was born with a very
dull and unfortunate character.”
The marquis appeared; Julien hastened to announce his
departure.
“Where to?” said M. de la Mole.
“For Languedoc.”
“No, if you please, you are reserved for higher destinies. If you
leave it will be for the North.... In military phraseology I actually
confine you in the hotel. You will compel me to be never more than
two or three hours away. I may have need of you at any moment.”
Julien bowed and retired without a word, leaving the marquis in a
state of great astonishment. He was incapable of speaking. He shut
himself up in his room. He was there free to exaggerate to himself
all the awfulness of his fate.
“So,” he thought, “I cannot even get away. God knows how many
days the marquis will keep me in Paris. Great God, what will become
of me, and not a friend whom I can consult? The abbé Pirard will
never let me finish my first sentence, while the comte Altamira will
propose enlisting me in some conspiracy. And yet I am mad; I feel it,
I am mad. Who will be able to guide me, what will become of me?”
CHAPTER XLVIII
CRUEL MOMENTS
And she confesses it to me! She goes into even the smallest
details! Her beautiful eyes fixed on mine, and describes the love
which she felt for another.—Schiller.
The delighted mademoiselle de la Mole thought of nothing but the
happiness of having been nearly killed. She went so far as to say to
herself, “he is worthy of being my master since he was on the point
of killing me. How many handsome young society men would have
to be melted together before they were capable of so passionate a
transport.”
“I must admit that he was very handsome at the time when he
climbed up on the chair to replace the sword in the same
picturesque position in which the decorator hung it! After all it was
not so foolish of me to love him.”
If at that moment some honourable means of reconciliation had
presented itself, she would have embraced it with pleasure. Julien
locked in his room was a prey to the most violent despair. He
thought in his madness of throwing himself at her feet. If instead of
hiding himself in an out of the way place, he had wandered about
the garden of the hôtel so as to keep within reach of any
opportunity, he would perhaps have changed in a single moment his
awful unhappiness into the keenest happiness.
But the tact for whose lack we are now reproaching him would
have been incompatible with that sublime seizure of the sword,
which at the present time rendered him so handsome in the eyes of
mademoiselle de la Mole. This whim in Julien’s favour lasted the
whole day; Mathilde conjured up a charming image of the short
moments during which she had loved him: she regretted them.
“As a matter of fact,” she said to herself, “my passion for this poor
boy can from his point of view only have lasted from one hour after
midnight when I saw him arrive by his ladder with all his pistols in
his coat pocket, till eight o’clock in the morning. It was a quarter of
an hour after that as I listened to mass at Sainte-Valère that I began
to think that he might very well try to terrify me into obedience.”
After dinner mademoiselle de la Mole, so far from avoiding Julien,
spoke to him and made him promise to follow her into the garden.
He obeyed. It was a new experience.
Without suspecting it Mathilde was yielding to the love which she
was now feeling for him again. She found an extreme pleasure in
walking by his side, and she looked curiously at those hands which
had seized the sword to kill her that very morning.
After such an action, after all that had taken place, some of the
former conversation was out of the question.
Mathilde gradually began to talk confidentially to him about the
state of her heart. She found a singular pleasure in this kind of
conversation, she even went so far as to describe to him the fleeting
moments of enthusiasm which she had experienced for M. de
Croisenois, for M. de Caylus——
“What! M. de Caylus as well!” exclaimed Julien, and all the
jealousy of a discarded lover burst out in those words, Mathilde
thought as much, but did not feel at all insulted.
She continued torturing Julien by describing her former sentiments
with the most picturesque detail and the accent of the most intimate
truth. He saw that she was portraying what she had in her mind’s
eye. He had the pain of noticing that as she spoke she made new
discoveries in her own heart.
The unhappiness of jealousy could not be carried further.
It is cruel enough to suspect that a rival is loved, but there is no
doubt that to hear the woman one adores confess in detail the love
which rivals inspires, is the utmost limit of anguish.
Oh, how great a punishment was there now for those impulses of
pride which had induced Julien to place himself as superior to the
Caylus and the Croisenois! How deeply did he feel his own
unhappiness as he exaggerated to himself their most petty
advantages. With what hearty good faith he despised himself.
Mathilde struck him as adorable. All words are weak to express his
excessive admiration. As he walked beside her he looked
surreptitiously at her hands, her arms, her queenly bearing. He was
so completely overcome by love and unhappiness as to be on the
point of falling at her feet and crying “pity.”
“Yes, and that person who is so beautiful, who is so superior to
everything and who loved me once, will doubtless soon love M. de
Caylus.”
Julien could have no doubts of mademoiselle de la Mole’s sincerity,
the accent of truth was only too palpable in everything she said. In
order that nothing might be wanting to complete his unhappiness
there were moments when, as a result of thinking about the
sentiments which she had once experienced for M. de Caylus,
Mathilde came to talk of him, as though she loved him at the
present time. She certainly put an inflection of love into her voice.
Julien distinguished it clearly.
He would have suffered less if his bosom had been filled inside
with molten lead. Plunged as he was in this abyss of unhappiness
how could the poor boy have guessed that it was simply because
she was talking to him, that mademoiselle de la Mole found so much
pleasure in recalling those weaknesses of love which she had
formerly experienced for M. de Caylus or M. de Luz.
Words fail to express Julien’s anguish. He listened to these
detailed confidences of the love she had experienced for others in
that very avenue of pines where he had waited so few days ago for
one o’clock to strike that he might invade her room. No human being
can undergo a greater degree of unhappiness.
This kind of familiar cruelty lasted for eight long days. Mathilde
sometimes seemed to seek opportunities of speaking to him and
sometimes not to avoid them; and the one topic of conversation to
which they both seemed to revert with a kind of cruel pleasure, was
the description of the sentiments she had felt for others. She told
him about the letters which she had written, she remembered their
very words, she recited whole sentences by heart.
She seemed during these last days to be envisaging Julien with a
kind of malicious joy. She found a keen enjoyment in his pangs.
One sees that Julien had no experience of life; he had not even
read any novels. If he had been a little less awkward and he had
coolly said to the young girl, whom he adored so much and who had
been giving him such strange confidences: “admit that though I am
not worth as much as all these gentlemen, I am none the less the
man whom you loved,” she would perhaps have been happy at being
at thus guessed; at any rate success would have entirely depended
on the grace with which Julien had expressed the idea, and on the
moment which he had chosen to do so. In any case he would have
extricated himself well and advantageously from a situation which
Mathilde was beginning to find monotonous.
“And you love me no longer, me, who adores you!” said Julien to
her one day, overcome by love and unhappiness. This piece of folly
was perhaps the greatest which he could have committed. These
words immediately destroyed all the pleasure which mademoiselle
de la Mole found in talking to him about the state of her heart. She
was beginning to be surprised that he did not, after what had
happened, take offence at what she told him. She had even gone so
far as to imagine at the very moment when he made that foolish
remark that perhaps he did not love her any more. “His pride has
doubtless extinguished his love,” she was saying to herself. “He is
not the man to sit still and see people like Caylus, de Luz, Croisenois
whom he admits are so superior, preferred to him. No, I shall never
see him at my feet again.”
Julien had often in the naivety of his unhappiness, during the
previous days praised sincerely the brilliant qualities of these
gentlemen; he would even go so far as to exaggerate them. This
nuance had not escaped mademoiselle de la Mole, she was
astonished by it, but did not guess its reason. Julien’s frenzied soul,
in praising a rival whom he thought was loved, was sympathising
with his happiness.
These frank but stupid words changed everything in a single
moment; confident that she was loved, Mathilde despised him
utterly.
She was walking with him when he made his ill-timed remark; she
left him, and her parting look expressed the most awful contempt.
She returned to the salon and did not look at him again during the
whole evening. This contempt monopolised her mind the following
day. The impulse which during the last week had made her find so
much pleasure in treating Julien as her most intimate friend was out
of the question; the very sight of him was disagreeable. The
sensation Mathilde felt reached the point of disgust; nothing can
express the extreme contempt which she experienced when her
eyes fell upon him.
Julien had understood nothing of the history of Mathilde’s heart
during the last week, but he distinguished the contempt. He had the
good sense only to appear before her on the rarest possible
occasions, and never looked at her.
But it was not without a mortal anguish that he, as it were,
deprived himself of her presence. He thought he felt his unhappiness
increasing still further. “The courage of a man’s heart cannot be
carried further,” he said to himself. He passed his life seated at a
little window at the top of the hôtel; the blind was carefully closed,
and from here at any rate he could see mademoiselle de la Mole
when she appeared in the garden.
What were his emotions when he saw her walking after dinner
with M. de Caylus, M. de Luz, or some other for whom she had
confessed to him some former amorous weakness!
Julien had no idea that unhappiness could be so intense; he was
on the point of shouting out. This firm soul was at last completely
overwhelmed.
Thinking about anything else except mademoiselle de la Mole had
become odious to him; he became incapable of writing the simplest
letters.
“You are mad,” the marquis said to him.
Julien was frightened that his secret might be guessed, talked
about illness and succeeded in being believed. Fortunately for him
the marquis rallied him at dinner about his next journey; Mathilde
understood that it might be a very long one. It was now several days
that Julien had avoided her, and the brilliant young men who had all
that this pale sombre being she had once loved was lacking, had no
longer the power of drawing her out of her reverie.
“An ordinary girl,” she said to herself, “would have sought out the
man she preferred among those young people who are the cynosure
of a salon; but one of the characteristics of genius is not to drive its
thoughts over the rut traced by the vulgar.
“Why, if I were the companion of a man like Julien, who only lacks
the fortune that I possess, I should be continually exciting attention,
I should not pass through life unnoticed. Far from incessantly fearing
a revolution like my cousins who are so frightened of the people that
they have not the pluck to scold a postillion who drives them badly, I
should be certain of playing a rôle and a great rôle, for the man
whom I have chosen has a character and a boundless ambition.
What does he lack? Friends, money? I will give them him.” But she
treated Julien in her thought as an inferior being whose love one
could win whenever one wanted.
CHAPTER XLIX
THE OPERA BOUFFE
How the spring of love resembleth
The uncertain glory of an April day,
Which now shows all the beauty of the sun,
And by and by a cloud takes all away.—
Shakespeare.
Engrossed by thoughts of her future and the singular rôle which
she hoped to play, Mathilde soon came to miss the dry metaphysical
conversations which she had often had with Julien. Fatigued by
these lofty thoughts she would sometimes also miss those moments
of happiness which she had found by his side; these last memories
were not unattended by remorse which at certain times even
overwhelmed her.
“But one may have a weakness,” she said to herself, “a girl like I
am should only forget herself for a man of real merit; they will not
say that it is his pretty moustache or his skill in horsemanship which
have fascinated me, but rather his deep discussions on the future of
France and his ideas on the analogy between the events which are
going to burst upon us and the English revolution of 1688.”
“I have been seduced,” she answered in her remorse. “I am a
weak woman, but at least I have not been led astray like a doll by
exterior advantages.”
“If there is a revolution why should not Julien Sorel play the rôle
of Roland and I the rôle of Madame Roland? I prefer that part to
Madame de Stael’s; the immorality of my conduct will constitute an
obstacle in this age of ours. I will certainly not let them reproach me
with an act of weakness; I should die of shame.”
Mathilde’s reveries were not all as grave, one must admit, as the
thoughts which we have just transcribed.
She would look at Julien and find a charming grace in his slightest
action.
“I have doubtless,” she would say, “succeeded in destroying in him
the very faintest idea he had of any one else’s rights.”
“The air of unhappiness and deep passion with which the poor boy
declared his love to me eight days ago proves it; I must own it was
very extraordinary of me to manifest anger at words in which there
shone so much respect and so much of passion. Am I not his real
wife? Those words of his were quite natural, and I must admit, were
really very nice. Julien still continued to love me, even after those
eternal conversations in which I had only spoken to him (cruelly
enough I admit), about those weaknesses of love which the
boredom of the life I lead had inspired me for those young society
men of whom he is so jealous. Ah, if he only knew what little danger
I have to fear from them; how withered and stereotyped they seem
to me in comparison with him.”
While indulging in these reflections Mathilde made a random
pencil sketch of a profile on a page of her album. One of the profiles
she had just finished surprised and delighted her. It had a striking
resemblance to Julien. “It is the voice of heaven. That’s one of the
miracles of love,” she cried ecstatically; “Without suspecting it, I
have drawn his portrait.”
She fled to her room, shut herself up in it, and with much
application made strenuous endeavours to draw Julien’s portrait, but
she was unable to succeed; the profile she had traced at random still
remained the most like him. Mathilde was delighted with it. She saw
in it a palpable proof of the grand passion.
She only left her album very late when the marquise had her
called to go to the Italian Opera. Her one idea was to catch sight of
Julien, so that she might get her mother to request him to keep
them company.
He did not appear, and the ladies had only ordinary vulgar
creatures in their box. During the first act of the opera, Mathilde
dreamt of the man she loved with all the ecstasies of the most vivid
passion; but a love-maxim in the second act sung it must be owned
to a melody worthy of Cimarosa pierced her heart. The heroine of
the opera said “You must punish me for the excessive adoration
which I feel for him. I love him too much.”
From the moment that Mathilde heard this sublime song
everything in the world ceased to exist. She was spoken to, she did
not answer; her mother reprimanded her, she could scarcely bring
herself to look at her. Her ecstasy reached a state of exultation and
passion analogous to the most violent transports which Julien had
felt for her for some days. The divinely graceful melody to which the
maxim, which seemed to have such a striking application to her own
position, was sung, engrossed all the minutes when she was not
actually thinking of Julien. Thanks to her love for music she was on
this particular evening like madame de Rênal always was, when she
thought of Julien. Love of the head has doubtless more intelligence
than true love, but it only has moments of enthusiasm. It knows
itself too well, it sits in judgment on itself incessantly; far from
distracting thought it is made by sheer force of thought.
On returning home Mathilde, in spite of madame de la Mole’s
remonstrances, pretended to have a fever and spent a part of the
night in going over this melody on her piano. She sang the words of
the celebrated air which had so fascinated her:—
Devo punirmi, devo punirmi.
Se troppo amai, etc.
As the result of this night of madness, she imagined that she had
succeeded in triumphing over her love. This page will be prejudicial
in more than one way to the unfortunate author. Frigid souls will
accuse him of indecency. But the young ladies who shine in the Paris
salons have no right to feel insulted at the supposition that one of
their number might be liable to those transports of madness which
have been degrading the character of Mathilde. That character is
purely imaginary, and is even drawn quite differently from that social
code which will guarantee so distinguished a place in the world’s
history to nineteenth century civilization.
The young girls who have adorned this winter’s balls are certainly
not lacking in prudence.
I do not think either that they can be accused of being unduly
scornful of a brilliant fortune, horses, fine estates and all the
guarantees of a pleasant position in society. Far from finding these
advantages simply equivalent to boredom, they usually concentrate
on them their most constant desires and devote to them such
passion as their hearts possess.
Nor again is it love which is the dominant principle in the career of
young men who, like Julien, are gifted with some talent; they attach
themselves with an irresistible grip to some côterie, and when the
côterie succeeds all the good things of society are rained upon them.
Woe to the studious man who belongs to no côterie, even his
smallest and most doubtful successes will constitute a grievance,
and lofty virtue will rob him and triumph. Yes, monsieur, a novel is a
mirror which goes out on a highway. Sometimes it reflects the azure
of the heavens, sometimes the mire of the pools of mud on the way,
and the man who carries this mirror in his knapsack is forsooth to be
accused by you of being immoral! His mirror shows the mire, and
you accuse the mirror! Rather accuse the main road where the mud
is, or rather the inspector of roads who allows the water to
accumulate and the mud to form.
Now that it is quite understood that Mathilde’s character is
impossible in our own age, which is as discreet as it is virtuous, I am
less frightened of offence by continuing the history of the follies of
this charming girl.
During the whole of the following day she looked out for
opportunities of convincing herself of her triumph over her mad
passion. Her great aim was to displease Julien in everything; but not
one of his movements escaped her.
Julien was too unhappy, and above all too agitated to appreciate
so complicated a stratagem of passion. Still less was he capable of
seeing how favourable it really was to him. He was duped by it. His
unhappiness had perhaps never been so extreme. His actions were
so little controlled by his intellect that if some mournful philosopher
had said to him, “Think how to exploit as quickly as you can those
symptoms which promise to be favourable to you. In this kind of
head-love which is seen at Paris, the same mood cannot last more
than two days,” he would not have understood him. But however
ecstatic he might feel, Julien was a man of honour. Discretion was
his first duty. He appreciated it. Asking advice, describing his agony
to the first man who came along would have constituted a happiness
analogous to that of the unhappy man who, when traversing a
burning desert receives from heaven a drop of icy water. He realised
the danger, was frightened of answering an indiscreet question by a
torrent of tears, and shut himself up in his own room.
He saw Mathilde walking in the garden for a long time. When she
at last left it, he went down there and approached the rose bush
from which she had taken a flower.
The night was dark and he could abandon himself to his
unhappiness without fear of being seen. It was obvious to him that
mademoiselle de la Mole loved one of those young officers with
whom she had chatted so gaily. She had loved him, but she had
realised his little merit, “and as a matter of fact I had very little,”
Julien said to himself with full conviction. “Taking me all round I am
a very dull, vulgar person, very boring to others and quite
unbearable to myself.” He was mortally disgusted with all his good
qualities, and with all the things which he had once loved so
enthusiastically; and it was when his imagination was in this
distorted condition that he undertook to judge life by means of its
aid. This mistake is typical of a superior man.
The idea of suicide presented itself to him several times; the idea
was full of charm, and like a delicious rest; because it was the glass
of iced water offered to the wretch dying of thirst and heat in the
desert.
“My death will increase the contempt she has for me,” he
exclaimed. “What a memory I should leave her.”
Courage is the only resource of a human being who has fallen into
this last abyss of unhappiness. Julien did not have sufficient genius
to say to himself, “I must dare,” but as he looked at the window of
Mathilde’s room he saw through the blinds that she was putting out
her light. He conjured up that charming room which he had seen,
alas! once in his whole life. His imagination did not go any further.
One o’clock struck. Hearing the stroke of the clock and saying to
himself, “I will climb up the ladder,” scarcely took a moment.
It was the flash of genius, good reasons crowded on his mind.
“May I be more fortunate than before,” he said to himself. He ran to
the ladder. The gardener had chained it up. With the help of the
cock of one of his little pistols which he broke, Julien, who for the
time being was animated by a superhuman force, twisted one of the
links of the chain which held the ladder. He was master of it in a few
minutes, and placed it against Mathilde’s window.
“She will be angry and riddle me with scornful words! What does it
matter? I will give her a kiss, one last kiss. I will go up to my room
and kill myself ... my lips will touch her cheek before I die.”
He flew up the ladder and knocked at the blind; Mathilde heard
him after some minutes and tried to open the blind but the ladder
was in the way. Julien hung to the iron hook intending to keep the
blind open, and at the imminent risk of falling down, gave the ladder
a violent shake which moved it a little. Mathilde was able to open
the blind.
He threw himself into the window more dead than alive.
“So it is you, dear,” she said as she rushed into his arms.
The excess of Julien’s happiness was indescribable. Mathilde’s
almost equalled his own.
She talked against herself to him and denounced herself.
“Punish me for my awful pride,” she said to him, clasping him in
her arms so tightly as almost to choke him. “You are my master,
dear, I am your slave. I must ask your pardon on my knees for
having tried to rebel.” She left his arms to fall at his feet. “Yes,” she
said to him, still intoxicated with happiness and with love, “you are
my master, reign over me for ever. When your slave tries to revolt,
punish her severely.”
In another moment she tore herself from his arms, and lit a
candle, and it was only by a supreme effort that Julien could prevent
her from cutting off a whole tress of her hair.
“I want to remind myself,” she said to him, “that I am your
handmaid. If I am ever led astray again by my abominable pride,
show me this hair and say, ‘It is not a question of the emotion which
your soul may be feeling at present, you have sworn to obey, obey
on your honour.’”
But it is wiser to suppress the description of so intense a transport
of delirious happiness.
Julien’s unselfishness was equal to his happiness. “I must go down
by the ladder,” he said to Mathilde, when he saw the dawn of day
appear from the quarter of the east over the distant chimneys
beyond the garden. “The sacrifice that I impose on myself is worthy
of you. I deprive myself of some hours of the most astonishing
happiness that a human soul can savour, but it is a sacrifice I make
for the sake of your reputation. If you know my heart you will
appreciate how violent is the strain to which I am putting myself.
Will you always be to me what you are now? But honour speaks, it
suffices. Let me tell you that since our last interview, thieves have
not been the only object of suspicion. M. de la Mole has set a guard
in the garden. M. Croisenois is surrounded by spies: they know what
he does every night.”
Mathilde burst out laughing at this idea. Her mother and a
chamber-maid were woken up, they suddenly began to speak to her
through the door. Julien looked at her, she grew pale as she scolded
the chamber-maid, and she did not deign to speak to her mother.
“But suppose they think of opening the window, they will see the
ladder,” Julien said to her.
He clasped her again in his arms, rushed on to the ladder, and
slid, rather than climbed down; he was on the ground in a moment.
Three seconds after the ladder was in the avenue of pines, and
Mathilde’s honour was saved. Julien returned to his room and found
that he was bleeding and almost naked. He had wounded himself in
sliding down in that dare-devil way.
Extreme happiness had made him regain all the energy of his
character. If twenty men had presented themselves it would have
proved at this moment only an additional pleasure to have attacked
them unaided. Happily his military prowess was not put to the proof.
He laid the ladder in its usual place and replaced the chain which
held it. He did not forget to efface the mark which the ladder had
left on the bed of exotic flowers under Mathilde’s window.
As he was moving his hand over the soft ground in the darkness
and satisfying himself that the mark had entirely disappeared, he felt
something fall down on his hands. It was a whole tress of Mathilde’s
hair which she had cut off and thrown down to him.
She was at the window.
“That’s what your servant sends you,” she said to him in a fairly
loud voice, “It is the sign of eternal gratitude. I renounce the
exercise of my reason, be my master.”
Julien was quite overcome and was on the point of going to fetch
the ladder again and climbing back into her room. Finally reason
prevailed.
Getting back into the hôtel from the garden was not easy. He
succeeded in forcing the door of a cellar. Once in the house he was
obliged to break through the door of his room as silently as possible.
In his agitation he had left in the little room which he had just
abandoned so rapidly, the key which was in the pocket of his coat. “I
only hope she thinks of hiding that fatal trophy,” he thought.
Finally fatigue prevailed over happiness, and as the sun was rising
he fell into a deep sleep.
The breakfast bell only just managed to wake him up. He
appeared in the dining-room. Shortly afterwards Mathilde came in.
Julien’s pride felt deliciously flattered as he saw the love which shone
in the eyes of this beautiful creature who was surrounded by so
much homage; but soon his discretion had occasion to be alarmed.
Making an excuse of the little time that she had had to do her hair,
Mathilde had arranged it in such a way that Julien could see at the
first glance the full extent of the sacrifice that she had made for his
sake, by cutting off her hair on the previous night.
If it had been possible to spoil so beautiful a face by anything
whatsoever, Mathilde would have succeeded in doing it. A whole
tress of her beautiful blonde hair was cut off to within half an inch of
the scalp.
Mathilde’s whole manner during breakfast was in keeping with this
initial imprudence. One might have said that she had made a specific
point of trying to inform the whole world of her mad passion for
Julien. Happily on this particular day M. de la Mole and the marquis
were very much concerned about an approaching bestowal of “blue
ribbons” which was going to take place, and in which M. de
Chaulnes was not comprised. Towards the end of the meal, Mathilde,
who was talking to Julien, happened to call him “My Master.” He
blushed up to the whites of his eyes.
Mathilde was not left alone for an instant that day, whether by
chance or the deliberate policy of madame de la Mole. In the
evening when she passed from the dining-room into the salon,
however, she managed to say to Julien: “You may be thinking I am
making an excuse, but mamma has just decided that one of her
women is to spend the night in my room.”
This day passed with lightning rapidity. Julien was at the zenith of
happiness. At seven o’clock in the morning of the following day he
installed himself in the library. He hoped the mademoiselle de la
Mole would deign to appear there; he had written her an
interminable letter. He only saw her several hours afterwards at
breakfast. Her hair was done to-day with the very greatest care; a
marvellous art had managed to hide the place where the hair had
been cut. She looked at Julien once or twice, but her eyes were
polite and calm, and there was no question of calling him “My
Master.”
Julien’s astonishment prevented him from breathing—Mathilde
was reproaching herself for all she had done for him. After mature
reflection, she had come to the conclusion that he was a person
who, though not absolutely commonplace, was yet not sufficiently
different from the common ruck to deserve all the strange follies that
she had ventured for his sake. To sum up she did not give love a
single thought; on this particular day she was tired of loving.
As for Julien, his emotions were those of a child of sixteen. He
was a successive prey to awful doubt, astonishment and despair
during this breakfast which he thought would never end.
As soon as he could decently get up from the table, he flew rather
than ran to the stable, saddled his horse himself, and galloped off. “I
must kill my heart through sheer force of physical fatigue,” he said to
himself as he galloped through the Meudon woods. “What have I
done, what have I said to deserve a disgrace like this?”
“I must do nothing and say nothing to-day,” he thought as he re-
entered the hôtel. “I must be as dead physically as I am morally.”
Julien saw nothing any more, it was only his corpse which kept
moving.
CHAPTER L
THE JAPANESE VASE
His heart does not first realise the full extremity of his
unhappiness: he is more troubled than moved. But as reason
returns he feels the depth of his misfortune. All the pleasures of
life seem to have been destroyed, he can only feel the sharp
barbs of a lacerating despair. But what is the use of talking of
physical pain? What pain which is only felt by the body can be
compared to this pain?—Jean Paul.
The dinner bell rang, Julien had barely time to dress: he found
Mathilde in the salon. She was pressing her brother and M. de
Croisenois to promise her that they would not go and spend the
evening at Suresnes with madame the maréchale de Fervaques.
It would have been difficult to have shown herself more amiable
or fascinating to them. M. de Luz, de Caylus and several of their
friends came in after dinner. One would have said that mademoiselle
de la Mole had commenced again to cultivate the most scrupulous
conventionality at the same time as her sisterly affection. Although
the weather was delightful this evening, she refused to go out into
the garden, and insisted on their all staying near the arm-chair
where madame de la Mole was sitting. The blue sofa was the centre
of the group as it had been in the winter.
Mathilde was out of temper with the garden, or at any rate she
found it absolutely boring: it was bound up with the memory of
Julien.
Unhappiness blunts the edge of the intellect. Our hero had the
bad taste to stop by that little straw chair which had formerly
witnessed his most brilliant triumphs. To-day none spoke to him, his
presence seemed to be unnoticed, and worse than that. Those of
mademoiselle de la Mole’s friends who were sitting near him at the
end of the sofa, made a point of somehow or other turning their
back on him, at any rate he thought so.
“It is a court disgrace,” he thought. He tried to study for a
moment the people who were endeavouring to overwhelm him with
their contempt. M. de Luz had an important post in the King’s suite,
the result of which was that the handsome officer began every
conversation with every listener who came along by telling him this
special piece of information. His uncle had started at seven o’clock
for St. Cloud and reckoned on spending the night there. This detail
was introduced with all the appearance of good nature but it never
failed to be worked in. As Julien scrutinized M. de Croisenois with a
stern gaze of unhappiness, he observed that this good amiable
young man attributed a great influence to occult causes. He even
went so far as to become melancholy and out of temper if he saw an
event of the slightest importance ascribed to a simple and perfectly
natural cause.
“There is an element of madness in this,” Julien said to himself.
This man’s character has a striking analogy with that of the Emperor
Alexander, such as the Prince Korasoff described it to me. During the
first year of his stay in Paris poor Julien, fresh from the seminary and
dazzled by the graces of all these amiable young people, whom he
found so novel, had felt bound to admire them. Their true character
was only beginning to become outlined in his eyes.
“I am playing an undignified rôle here,” he suddenly thought. The
question was, how he could leave the little straw chair without
undue awkwardness. He wanted to invent something, and tried to
extract some novel excuse from an imagination which was otherwise
engrossed. He was compelled to fall back on his memory, which was,
it must be owned, somewhat poor in resources of this kind.
The poor boy was still very much out of his element, and could
not have exhibited a more complete and noticeable awkwardness
when he got up to leave the salon. His misery was only too palpable
in his whole manner. He had been playing, for the last three quarters
of an hour, the rôle of an officious inferior from whom one does not
take the trouble to hide what one really thinks.
The critical observations he had just made on his rivals prevented
him, however, from taking his own unhappiness too tragically. His
pride could take support in what had taken place the previous day.
“Whatever may be their advantages over me,” he thought, as he
went into the garden alone, “Mathilde has never been to a single
one of them what, twice in my life, she has deigned to be to me!”
His penetration did not go further. He absolutely failed to appreciate
the character of the extraordinary person whom chance had just
made the supreme mistress of all his happiness.
He tried, on the following day, to make himself and his horse dead
tired with fatigue. He made no attempt in the evening to go near the
blue sofa to which Mathilde remained constant. He noticed that
comte Norbert did not even deign to look at him when he met him
about the house. “He must be doing something very much against
the grain,” he thought; “he is naturally so polite.”
Sleep would have been a happiness to Julien. In spite of his
physical fatigue, memories which were only too seductive
commenced to invade his imagination. He had not the genius to see
that, inasmuch as his long rides on horseback over forests on the
outskirts of Paris only affected him, and had no affect at all on
Mathilde’s heart or mind, he was consequently leaving his eventual
destiny to the caprice of chance. He thought that one thing would
give his pain an infinite relief: it would be to speak to Mathilde. Yet
what would he venture to say to her?
He was dreaming deeply about this at seven o’clock one morning
when he suddenly saw her enter the library.
“I know, monsieur, that you are anxious to speak to me.”
“Great heavens! who told you?”
“I know, anyway; that is enough. If you are dishonourable, you
can ruin me, or at least try to. But this danger, which I do not
believe to be real, will certainly not prevent me from being sincere. I
do not love you any more, monsieur, I have been led astray by my
foolish imagination.”
Distracted by love and unhappiness, as a result of this terrible
blow, Julien tried to justify himself. Nothing could have been more
absurd. Does one make any excuses for failure to please? But reason
had no longer any control over his actions. A blind instinct urged him
to get the determination of his fate postponed. He thought that, so
long as he kept on speaking, all could not be over. Mathilde had not
listened to his words; their sound irritated her. She could not
conceive how he could have the audacity to interrupt her.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
textbookfull.com

More Related Content

Similar to Node js Design Patterns Master best practices to build modular and scalable server side web applications 2nd Edition Casciaro (20)

PPTX
Nodejs web service for starters
Bruce Li
 
PPTX
Mastering the Art of Node.js: Development Services for Success
NareshPatel726207
 
PDF
8 tips for mastering node.js
Solution Analysts
 
PDF
8 tips for mastering node.js
Solution Analysts
 
PPTX
Hire Leading Nodejs Development Service Providers in 2022.pptx
75waytechnologies
 
PDF
Node JS Express: Steps to Create Restful Web App
Edureka!
 
PDF
Learning Nodejs For Net Developers Harry Cummings
coeldiad
 
PPTX
Node.js Chapter1
Talentica Software
 
PDF
What is Node.js_ Where, When & How To Use It.pdf
Smith Daniel
 
PPTX
Introduction Node.js
Erik van Appeldoorn
 
PDF
9 anti-patterns for node.js teams
Jeff Harrell
 
PDF
Node.JS briefly introduced
Alexandre Lachèze
 
PDF
Jaap : node, npm & grunt
Bertrand Chevrier
 
PDF
NodeJS
Predhin Sapru
 
PPT
18_Node.js.ppt
KhalilSalhi7
 
PDF
Practical Node js Building Real World Scalable Web Apps 1st Edition Azat Mard...
seneydomanp1
 
PPT
18_Node.js.ppt
MaulikShah516542
 
PDF
Node.js.pdf
gulfam ali
 
PDF
Introduction to nodejs
James Carr
 
PDF
Node.js for beginner
Sarunyhot Suwannachoti
 
Nodejs web service for starters
Bruce Li
 
Mastering the Art of Node.js: Development Services for Success
NareshPatel726207
 
8 tips for mastering node.js
Solution Analysts
 
8 tips for mastering node.js
Solution Analysts
 
Hire Leading Nodejs Development Service Providers in 2022.pptx
75waytechnologies
 
Node JS Express: Steps to Create Restful Web App
Edureka!
 
Learning Nodejs For Net Developers Harry Cummings
coeldiad
 
Node.js Chapter1
Talentica Software
 
What is Node.js_ Where, When & How To Use It.pdf
Smith Daniel
 
Introduction Node.js
Erik van Appeldoorn
 
9 anti-patterns for node.js teams
Jeff Harrell
 
Node.JS briefly introduced
Alexandre Lachèze
 
Jaap : node, npm & grunt
Bertrand Chevrier
 
18_Node.js.ppt
KhalilSalhi7
 
Practical Node js Building Real World Scalable Web Apps 1st Edition Azat Mard...
seneydomanp1
 
18_Node.js.ppt
MaulikShah516542
 
Node.js.pdf
gulfam ali
 
Introduction to nodejs
James Carr
 
Node.js for beginner
Sarunyhot Suwannachoti
 

Recently uploaded (20)

PPTX
How to use _name_search() method in Odoo 18
Celine George
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
PPTX
SYMPATHOMIMETICS[ADRENERGIC AGONISTS] pptx
saip95568
 
PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PPT
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
PDF
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
PDF
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PDF
VCE Literature Section A Exam Response Guide
jpinnuck
 
DOCX
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
PPTX
Martyrs of Ireland - who kept the faith of St. Patrick.pptx
Martin M Flynn
 
PPTX
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
PDF
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
PDF
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 
PPTX
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
PDF
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
PPTX
Peer Teaching Observations During School Internship
AjayaMohanty7
 
PPTX
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
How to use _name_search() method in Odoo 18
Celine George
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
SYMPATHOMIMETICS[ADRENERGIC AGONISTS] pptx
saip95568
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
VCE Literature Section A Exam Response Guide
jpinnuck
 
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
Martyrs of Ireland - who kept the faith of St. Patrick.pptx
Martin M Flynn
 
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
 
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
Peer Teaching Observations During School Internship
AjayaMohanty7
 
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
Ad

Node js Design Patterns Master best practices to build modular and scalable server side web applications 2nd Edition Casciaro

  • 1. Node js Design Patterns Master best practices to build modular and scalable server side web applications 2nd Edition Casciaro download https://textbookfull.com/product/node-js-design-patterns-master- best-practices-to-build-modular-and-scalable-server-side-web- applications-2nd-edition-casciaro/ Download more ebook from https://textbookfull.com
  • 2. We believe these products will be a great fit for you. Click the link to download now, or visit textbookfull.com to discover even more! Node js web development server side development with Node 10 made easy Fourth Edition. Edition David Herron https://textbookfull.com/product/node-js-web-development-server- side-development-with-node-10-made-easy-fourth-edition-edition- david-herron/ Pro Express js Master Express js The Node js Framework For Your Web Development Mardan Azat https://textbookfull.com/product/pro-express-js-master-express- js-the-node-js-framework-for-your-web-development-mardan-azat/ RESTful Web API Design with Node js 10 Learn to create robust RESTful web services with Node js MongoDB and Express js 3rd Edition English Edition Valentin Bojinov https://textbookfull.com/product/restful-web-api-design-with- node-js-10-learn-to-create-robust-restful-web-services-with-node- js-mongodb-and-express-js-3rd-edition-english-edition-valentin- bojinov/ Learning Node js Development Learn the fundamentals of Node js and deploy and test Node js applications on the web 1st Edition Andrew Mead https://textbookfull.com/product/learning-node-js-development- learn-the-fundamentals-of-node-js-and-deploy-and-test-node-js- applications-on-the-web-1st-edition-andrew-mead/
  • 3. Django Design Patterns and Best Practices 2nd Edition Arun Ravindran https://textbookfull.com/product/django-design-patterns-and-best- practices-2nd-edition-arun-ravindran/ Node js 8 the Right Way Practical Server Side JavaScript That Scales 1st Edition Jim Wilson https://textbookfull.com/product/node-js-8-the-right-way- practical-server-side-javascript-that-scales-1st-edition-jim- wilson/ Node js for Embedded Systems Using Web Technologies to Build Connected Devices 1st Edition Patrick Mulder https://textbookfull.com/product/node-js-for-embedded-systems- using-web-technologies-to-build-connected-devices-1st-edition- patrick-mulder/ Node js MongoDB and Angular Web Development The definitive guide to using the MEAN stack to build web applications Developer s Library 2nd Edition Brad Dayley & Brendan Dayley & Caleb Dayley https://textbookfull.com/product/node-js-mongodb-and-angular-web- development-the-definitive-guide-to-using-the-mean-stack-to- build-web-applications-developer-s-library-2nd-edition-brad- dayley-brendan-dayley-caleb-dayley/ Ultimate Node.js for Cross-Platform App Development: Learn to Build Robust, Scalable, and Performant Server- Side JavaScript Applications with Node.js (English Edition) Kumar https://textbookfull.com/product/ultimate-node-js-for-cross- platform-app-development-learn-to-build-robust-scalable-and- performant-server-side-javascript-applications-with-node-js-
  • 5. Table of Contents Chapter 1: Welcome to the Node.js platform 1 The Node.js philosophy 1 Small core 2 Small modules 2 Small surface area 3 Simplicity and pragmatism 4 Introduction to Node 5 and ES2015 5 Arrow Function 5 Let and Const 7 Class syntax 8 Enhanced Object literals 9 Map and Set collections 11 WeakMap and WeakSet collections 13 Template Literals 13 The reactor pattern 14 I/O is slow 14 Blocking I/O 15 Non-blocking I/O 16 Event demultiplexing 17 The reactor pattern 19 The non-blocking I/O engine of Node.js – libuv 21 The recipe for Node.js 22 Summary 23 Chapter 2: Node.js Essential Patterns 25 The callback pattern 25 The continuation-passing style 26 Synchronous continuation-passing style 26 Asynchronous continuation-passing style 27 Non continuation-passing style callbacks 28 Synchronous or asynchronous? 29 An unpredictable function 29 Unleashing Zalgo 29 Using synchronous APIs 31 Deferred execution 32 Node.js callback conventions 33
  • 6. [ ii ] Callbacks come last 33 Error comes first 34 Propagating errors 34 Uncaught exceptions 35 The module system and its patterns 37 The revealing module pattern 37 Node.js modules explained 37 A homemade module loader 38 Defining a module 40 Defining globals 40 module.exports vs exports 40 Function require is synchronous 41 The resolving algorithm 42 The module cache 43 Cycles 44 Module definition patterns 45 Named exports 45 Exporting a function 46 Exporting a constructor 47 Exporting an instance 48 Modifying other modules or the global scope 49 The observer pattern 50 The EventEmitter 51 Create and use an EventEmitter 52 Propagating errors 53 Make any object observable 53 Synchronous and asynchronous events 55 EventEmitter vs Callbacks 56 Combine callbacks and EventEmitter 57 Summary 58 Chapter 3: Asynchronous Control Flow Patterns With Callbacks 59 The difficulties of asynchronous programming 59 Creating a simple web spider 60 The callback hell 62 Using plain JavaScript 63 Callback discipline 64 Applying the callback discipline 64 Sequential execution 67 Executing a known set of tasks in sequence 67 Sequential iteration 68 Web spider version 2 68
  • 7. [ iii ] Sequential crawling of links 69 The pattern 70 Parallel execution 71 Web spider version 3 74 The pattern 75 Fixing race conditions with concurrent tasks 76 Limited parallel execution 77 Limiting the concurrency 78 Globally limiting the concurrency 79 Queues to the rescue 80 Web spider version 4 81 The async library 82 Sequential execution 82 Sequential execution of a known set of tasks 83 Sequential iteration 85 Parallel execution 86 Limited parallel execution 86 Summary 88 Index 89
  • 8. 1 Welcome to the Node.js platform Some principles and design patterns literally define the Node.js platform and its ecosystem; the most peculiar ones are probably its asynchronous nature and its programming style that makes heavy use of callbacks. It's important that we first dive into these fundamental principles and patterns, not only for writing correct code, but also to be able to take effective design decisions when it comes to solving bigger and more complex problems. Another aspect that characterizes Node.js is its philosophy. Approaching Node.js is in fact way more than simply learning a new technology; it's also embracing a culture and a community. We will see how this greatly influences the way we design our applications and components, and the way they interact with those created by the community. In addition to these aspects it's worth knowing that the latest versions of Node.js introduced support for many of the features described by ES2015, which makes the language even more expressive and enjoyable to use. It is important to embrace these new syntactical and functional additions to the language to be able to produce more concise and readable code and come up with alternative ways to implement the design patterns that we are going to see throughout this book. In this chapter, we will learn the following topics: The Node.js philosophy, the “Node way” Node 5 and ES2015 The reactor pattern: the mechanism at the heart of the Node.js asynchronous architecture
  • 9. Welcome to the Node.js platform [ 2 ] The Node.js philosophy Every platform has its own philosophy-a set of principles and guidelines that are generally accepted by the community, an ideology of doing things that influences the evolution of a platform, and how applications are developed and designed. Some of these principles arise from the technology itself, some of them are enabled by its ecosystem, some are just trends in the community, and others are evolutions of different ideologies. In Node.js, some of these principles come directly from its creator, Ryan Dahl, from all the people who contributed to the core, from charismatic figures in the community, and some of the principles are inherited from the JavaScript culture or are influenced by the Unix philosophy. None of these rules are imposed and they should always be applied with common sense; however, they can prove to be tremendously useful when we are looking for a source of inspiration while designing our programs. You can find an extensive list of software development philosophies in Wikipedia at http://en.wikipedia.org/wiki/List_of_software_development _philosophies Small core The Node.js core itself has its foundations built on a few principles; one of these is, having the smallest set of functionality, leaving the rest to the so-called userland (or userspace),the ecosystem of modules living outside the core. This principle has an enormous impact on the Node.js culture, as it gives freedom to the community to experiment and iterate fast on a broader set of solutions within the scope of the userland modules, instead of being imposed with one slowly evolving solution that is built into the more tightly controlled and stable core. Keeping the core set of functionality to the bare minimum then, not only becomes convenient in terms of maintainability, but also in terms of the positive cultural impact that it brings on the evolution of the entire ecosystem. Small modules Node.js uses the concept of module as a fundamental mean to structure the code of a program. It is the brick for creating applications and reusable libraries called packages (a package is also frequently referred to as just module; since, usually it has one single module as an entry point). In Node.js, one of the most evangelized principles is to design small modules, not only in terms of code size, but most importantly in terms of scope.
  • 10. Welcome to the Node.js platform [ 3 ] This principle has its roots in the Unix philosophy, particularly in two of its precepts, which are as follows: “Small is beautiful.” “Make each program do one thing well.” Node.js brought these concepts to a whole new level. Along with the help of npm, the official package manager, Node.js helps solving the dependency hell problem by making sure that each installed package will have its own separate set of dependencies, thus enabling a program to depend on a lot of packages without incurring in conflicts. The Node way, in fact, involves extreme levels of reusability, whereby applications are composed of a highnumber of small, well-focused dependencies. While this can be considered unpractical or even totally unfeasible in other platforms, in Node.js this practice is encouraged. As a consequence, it is not rare to find npm packages containing less than 100 lines of code or exposing only one single function. Besides the clear advantage in terms of reusability, a small module is also considered to be the following: Easier to understand and use Simpler to test and maintain Perfect to share with the browser Having smaller and more focused modules empowers everyone to share or reuse even the smallest piece of code; it's the Don't Repeat Yourself (DRY) principle applied at a whole new level. Small surface area In addition to being small in size and scope, Node.js modules usually also have the characteristic of exposing only a minimal set of functionality. The main advantage here is an increased usability of the API, which means that the API becomes clearer to use and is less exposed to erroneous usage. Most of the time, in fact, the user of a component is interested only in a very limited and focused set of features, without the need to extend its functionality or tap into more advanced aspects. In Node.js, a very common pattern for defining modules is to expose only one piece of functionality, such as a function or a constructor, while letting more advanced aspects or secondary features become properties of the exported function or constructor. This helps the user to identify what is important and what is secondary. It is not rare to find modules that expose only one function and nothing else, for the simple fact that it provides a single,
  • 11. Welcome to the Node.js platform [ 4 ] unmistakably clear entry point. Another characteristic of many Node.js modules is the fact that they are created to be used rather than extended. Locking down the internals of a module by forbidding any possibility of an extension might sound inflexible, but it actually has the advantage of reducing the use cases, simplifying its implementation, facilitating its maintenance, and increasing its usability. Simplicity and pragmatism Have you ever heard of the Keep It Simple, Stupid (KISS) principle? Or the famous quote: “Simplicity is the ultimate sophistication.” – Leonardo da Vinci Richard P. Gabriel, a prominent computer scientist coined the term worse is better to describe the model, whereby less and simpler functionality is a good design choice for software. In his essay,The rise of worse is better, he says: “The design must be simple, both in implementation and interface. It is more important for the implementation to be simple than the interface. Simplicity is the most important consideration in a design.” Designing a simple, as opposed to a perfect, feature-full software, is a good practice for several reasons: it takes less effort to implement, allows faster shipping with less resources, is easier to adapt, and is easier to maintain and understand. These factors foster the community contributions and allow the software itself to grow and improve. In Node.js, this principle is also enabled by JavaScript, which is a very pragmatic language. It's not rare, in fact, to see simple functions, closures, and object literals replacing complex class hierarchies. Pure object-oriented designs often try to replicate the real world using the mathematical terms of a computer system without considering the imperfection and the complexity of the real world itself. The truth is that our software is always an approximation of the reality and we would probably have more success in trying to get something working sooner and with reasonable complexity, instead of trying to create a near-perfect software with a huge effort and tons of code to maintain. Throughout this book, we will see this principle in action many times. For example, a considerable number of traditional design patterns, such as Singleton or Decorator can have a trivial, even if sometimes not foolproof implementation and we will see how an uncomplicated, practical approach most of the time is preferred to a pure, flawless design.
  • 12. Welcome to the Node.js platform [ 5 ] Introduction to Node 5 and ES2015 At the time of writing the most recent major versions of Node.js (Node 4 and Node 5) come with a great addition to the language: a wide support for many of the new features introduced in the ECMAScript 2015 specification (in short ES2015 and formerly known also as ES6) which aims to make the language even more flexible and enjoyable. Throughout this book, we will widely adopt some of these new features in the code examples. These concepts are still fresh within the Node.js community so it's worth having a quick look at the most important ES2015 specific features currently supported in Node.js. Our version of reference is Node 5, more specifically version 5.1. Many of these features will work correctly only when the strict mode is enabled. Strict mode can be easily enabled by adding ause strict; statement at the very beginning of your script. For the sake of brevity, we will not write this line in our code examples but you should remember to add it to be able to run them correctly. The following list is not meant to be exhaustive but just an introduction to the ES2015 features supported in Node, so that you can easily understand all the code examples in the rest of this book. Arrow Function One of the most appreciated features introduced by ES2015 is the support for arrow functions. Arrow function is a more concise syntax for defining functions, especially useful when defining a callback. To better understand the advantages of this syntax let's see first an example of a classic filtering on an array: var numbers = [2, 6, 7, 8, 1]; var even = numbers.filter(function(x) { return x%2 === 0; }); This code above can be rewritten as follows using the arrow function syntax: var numbers = [2, 6, 7, 8, 1]; var even = numbers.filter((x) => x%2 === 0); The filter function can be defined inline, the keyword function is removed, leaving only the list of parameters, which is followed by => (the arrow), which in turn is followed by the body of the function. When the body of the function is just one line there's no need to write the return keyword as it is applied implicitly. If we need to add more lines of code to the body of the function, we can wrap them in curly brackets, but beware that in this case the
  • 13. Welcome to the Node.js platform [ 6 ] return is not automatically implied, so it needs to be stated explicitly, as in the following example: var numbers = [2, 6, 7, 8, 1]; var even = numbers.filter((x) => { if (x%2 === 0) { console.log(x + ' is even!'); return true; } }); But there is another important feature to know about arrow functions: arrow functions are bound to their lexical scope. This means that inside an arrow function the value of this is the same as in the parent block. Let's clarify this concept with an example: function DelayedGreeter(name) { this.name = name; } DelayedGreeter.prototype.greet = function() { setTimeout( function cb() { console.log('Hello ' + this.name); }, 500); }; let greeter = new DelayedGreeter('World'); greeter.greet(); // will print "Hello undefined" In this code we are defining a simple “greeter” prototype which accepts a name as argument. Then we are adding the greet method to the prototype. This function is supposed to print “Hello” and the name defined in the current instance after 500 milliseconds it has been called. But this function is broken because inside the timeout callback function (cb), the scope of the function is different from the scope of the greet method and the value of this is undefined. Before Node.js introduced support for arrow functions, to fix this we needed to change the greet function using bind as follows: DelayedGreeter.prototype.greet = function() { setTimeout( (function cb() { console.log('Hello ' + this.name); }).bind(this), 500); }; But since we have now arrow functions and since they are bound to their lexical scope, we can just use an arrow function as callback to solve the issue:
  • 14. Welcome to the Node.js platform [ 7 ] DelayedGreeter.prototype.greet = function() { setTimeout( () => console.log('Hello ' + this.name), 500); }; This is a very handy feature, most of the time it makes our code more concise and straightforward. Let and Const Historically JavaScript offered only function scope and global scope to control the lifetime and the visibility of a variable. For instance if you declare a variable inside the body of an if statement the variable will be accessible even outside the statement, whether or not the body of the statement has been executed. Let's see it more clearly with an example: if (false) { var x = "hello"; } console.log(x); This code will not fail as we might expect and it will just print undefined in the console. This behavior has been cause of many bugs and frustration and that is the reason why ES2015 introduces the let keyword to declare variables that respect the block scope. Let's replace var with let in our previous example: if (false) { let x = "hello"; } console.log(x); This code will raise a ReferenceError: x is not defined because we are trying to print a variable that has been defined inside another block scope. To give a more meaningful example we can use the let keyword to define a temporary variable to be used as an index for a loop: for (let i=0; i < 10; i++) { // do something here } console.log(i); As in the previous example, this code will raise a ReferenceError: i is not defined error. This protective behavior introduced with let allows us to write safer code, because if we accidentally access variables that belong to another scope we will get an error that will
  • 15. Welcome to the Node.js platform [ 8 ] allow us to easily spot the bug and avoid potentially dangerous side effects. ES2015 introduces also the const keyword. This keyword allows to declare read-only variables. Let's see a quick example: const x = 'This will never change'; x = '...'; This code will raise a “TypeError: Assignment to constant variable” error because we are trying to change the value of a constant. Constants are extremely useful when you want to protect a value from being accidentally changed in your code. Class syntax ES2015 introduces a new syntax to leverage prototypical inheritance in a way that should sound more familiar to all the developers that come from classic object oriented languages such as Java or C#. It's important to underline that this new syntax does not change the way objects are managed internally by the JavaScript runtime, they still inherits properties and functions through prototypes and not through classes. While this new alternative syntax can be very handy and readable, as a developer is important to understand that it is just a syntactic sugar. Let's see how it works with a trivial example. First of all, let's describe a Person using the classic prototype based approach: function Person(name, surname, age) { this.name = name; this.surname = surname; this.age = age; } Person.prototype.getFullName = function() { return this.name + ' ' + this.surname; } Person.older = function(person1, person2) { return (person1.age >= person2.age) ? person1 : person2; } As you can see a person has a name, a surname and an age. We are providing to our prototype a helper function that allows us to easily get the full name of a person object and a generic helper function accessible directly from the Person prototype that returns the
  • 16. Welcome to the Node.js platform [ 9 ] older person between two Person instances given as input. Let's see now how we can implement the same example using the new handy ES2015 class syntax: class Person { constructor (name, surname, age) { this.name = name; this.surname = surname; this.age = age; } getFullName () { return this.name + ' ' + this.surname; } static older (person1, person2) { return (person1.age >= person2.age) ? person1 : person2; } } This syntax results more readable and straightforward to understand. We are explicitly stating what is the constructor for the class and declaring the function older as a static method. Both implementations are completely interchangeable, but the real killer feature of the new syntax is the possibility of extending the Person prototype using the extend and the super keywords. Let's assume we want to create the PersonWithMiddlename class: class PersonWithMiddlename extends Person { constructor (name, middlename, surname, age) { super(name, surname, age); this.middlename = middlename; } getFullName () { return this.name + ' ' + this.middlename + ' ' + this.surname; } } What is worth noticing in this second example is that the syntax really resembles what is common in other object oriented languages. We are declaring the class from which we want to extend, we define a new constructor that can call the parent one using the keyword super and we override the getFullName method to add support for our middle name.
  • 17. Welcome to the Node.js platform [ 10 ] Enhanced Object literals As long with the new class syntax, ES2015 introduced an enhanced object literals syntax. This syntax offers a shorthand to assign variables and functions as members of the object, allows to define computed member names at creation time and also handy setters and getters methods. Let's make all of this clear with some examples: let x = 22; let y = 17; let obj = { x, y }; obj will be an object containing the keys x and y, respectively with the values 22 and 17. We can do the same thing with functions: module.exports = { square (x) { return x * x; }, cube (x) { return x * x * x; } }; In this case we are writing a module that exports the functions square and cube mapped to properties with the same name. Notice that we don't need to specify the keyword function. Let's see in another example how we can use computed property names: let namespace = '-webkit-'; let style = { [namespace + 'box-sizing'] : 'border-box', [namespace + 'box-shadow'] : '10px 10px 5px #888888' }; In this case the resulting object will contain the properties -webkit-box-sizing and - webkit-box-shadow. Let's see now how we can use the new setter and getter syntax by jumping directly to an example: let person = { name : 'George', surname : 'Boole',
  • 18. Welcome to the Node.js platform [ 11 ] get fullname () { return this.name + ' ' + this.surname; }, set fullname (fullname) { let parts = fullname.split(' '); this.name = parts[0]; this.surname = parts[1]; } } console.log(person.fullname); // "George Boole" console.log(person.fullname = 'Alan Turing'); // "Alan Turing" console.log(person.name); // "Alan" In this example we are defining three properties, two normal name and surname and a computed property fullname through the set and get syntax. As you can see from the result of the console.log calls, we can access the computed property as if it was a regular property inside the object for both reading and writing the value. It's worth noticing that the second call to console.log prints “Alan Turing”. This happens because by default every set function returns the value that is returned by the get function for the same property, in this case get fullname. Map and Set collections As JavaScript developers we are used to create hash maps using plain objects. ES2015 introduces a new prototype called Map that is specifically designed to leverage hash map collections in a more secure, flexible and intuitive way. Let's see a quick example: let profiles = new Map(); profiles.set('twitter', '@adalovelace'); profiles.set('facebook', 'adalovelace'); profiles.set('googleplus', 'ada'); profiles.size; // 3 profiles.has('twitter'); // true profiles.get('twitter'); // "@adalovelace" profiles.has('youtube'); // false profiles.delete('facebook'); profiles.has('facebook'); // false profiles.get('facebook'); // undefined for (let entry of profiles) { console.log(entry); }
  • 19. Welcome to the Node.js platform [ 12 ] As you can see the Map prototype offers several handy methods like set, get, has and delete and the size attribute. We can also iterate through all the entries using the for ... of syntax. Every entry in the loop will be an array containing the key as first element and the value as second element. This interface is very intuitive and self-explanatory. But what makes maps really interesting is the possibility of using functions and objects as keys of the map and this was something that is not entirely possible using plain objects, because with objects all the keys are automatically casted to strings. This opens new opportunities, for example we can build a micro testing framework leveraging this feature: let tests = new Map(); tests.set(() => 2+2, 4); tests.set(() => 2*2, 4); tests.set(() => 2/2, 1); for (let entry of tests) { console.log((entry[0]() === entry[1]) ? ' ' : ' '); } As you can see in this last example, we are storing functions as keys and expected results as values. Then we can iterate through our hash map and execute all the functions. It's also worth noticing that when we iterate through the map all the entries respect the order in which they have been inserted, this is also something that was not always guaranteed with plain objects. Along with Map, ES2015 also introduces the Set prototype. This prototype allows us to easily construct sets, which means lists with unique values. let s = new Set([0, 1, 2, 3]); s.add(3); // will not be added s.size; // 4 s.delete(0); s.has(0); // false for (let entry of s) { console.log(entry); } As you can see in this example the interface is quite similar to the one we have just seen for
  • 20. Welcome to the Node.js platform [ 13 ] Map. We have the methods add (instead of set), has and delete and the property size. We can also iterate through the set and in this case every entry is a value, in our example it will be one of the numbers in the set. Finally, sets can also contain objects and functions as values. WeakMap and WeakSet collections ES2015 defines also a weak version of the Map and the Set prototypes called WeakMap and WeakSet. WeakMap is quite similar to Map in terms of interface, there are only two main differences: there is no way to iterate all over the entries and it allows to have only objects as keys. While this might seem as a limitation there is a good reason behind it, in fact the distinctive feature of WeakMap is that it allows objects used as keys to be garbage collected when the only reference left is inside a WeakMap. This is extremely useful when we are storing some metadata associated to an object that might get deleted during the regular lifetime of the application. Let's see an example: let obj = {}; let map = new WeakMap(); map.set(obj, {metadata: "some_metadata"}); console.log(map.get(obj)); // {metadata: "some_metadata"} obj = undefined; // now obj and metadata will be cleaned up in the next gc cycle In this code we are creating a plain object called obj. Then we store some metadata for this object in a new WeakMap called map. We can access this metadata with the map.get method. Later, when we cleanup the object by assigning its variable to undefined, the object will be correctly garbage collected and its metadata removed from the map. Similarly, to WeakMap, WeakSet is the weak version of Set: it exposes the same interface of Set but it allows to store only objects and cannot be iterated. Again the difference with Set is that WeakSet allows objects to be garbage collected when their only reference left is in the weak set. It's important to understand that WeakMap and WeakSet are not better or worse than Map and Set, they are simply more suitable for different use cases. Template Literals ES2015 offers a new alternative and more powerful syntax to define strings: the template
  • 21. Welcome to the Node.js platform [ 14 ] literals. This syntax uses back ticks (`) as delimiters and offers several benefits compared to regular quoted (') or double-quoted (") delimited strings. The main ones are that template literals syntax can interpolate variables or expressions using ${expression} inside the string (this is the reason why this syntax is called “template”) and that strings can finally be multiline. Let's see a quick example: let name = "Leonardo"; let interests = ["arts", "architecture", "science", "music", "mathematics"]; let birth = { year : 1452, place : 'Florence' }; let text = `${name} was an Italian polymath interested in many topics such as ${interests.join(', ')}. He was born in ${birth.year} in ${birth.place}.`; console.log(text); This code will print: Leonardo was an Italian polymath interested in many topics such as arts, architecture, science, music, mathematics. He was born in 1452 in Florence. A more extended and up to date list of all the supported ES2015 features is available in the official Node.js documentation: https://nodejs.org/en/docs/es6/ The reactor pattern In this section, we will analyze the reactor pattern, which is the heart of the Node.js asynchronous nature. We will go through the main concepts behind the pattern, such as the single-threaded architecture and the non-blocking I/O, and we will see how this creates the foundation for the entire Node.js platform. I/O is slow I/O is definitely the slowest among the fundamental operations of a computer. Accessing the RAM is in the order of nanoseconds (10e -9 seconds), while accessing data on the disk or the network is in the order of milliseconds (10e-3 seconds). For the bandwidth, it is the same story; RAM has a transfer rate consistently in the order of GB/s, while disk and network varies from MB/s to, optimistically, GB/s. I/O is usually not expensive in terms of CPU, but it adds a delay between the moment the request is sent and the moment the operation completes. On top of that, we also have to consider thehuman factor; often, the input of an
  • 22. Welcome to the Node.js platform [ 15 ] application comes from a real person, for example, the click of a button or a message sent in a real-time chat application, so the speed and frequency of I/O don't depend only on technical aspects, and they can be many orders of magnitude slower than the disk or network. Blocking I/O In traditional blocking I/O programming, the function call corresponding to an I/O request will block the execution of the thread until the operation completes. This can go from a few milliseconds, in case of a disk access, to minutes or even more, in case the data is generated from user actions, such as pressing a key. The following pseudocode shows a typical blocking read performed against a socket: //blocks the thread until the data is available data = socket.read(); //data is available print(data); It is trivial to notice that a web server that is implemented using blocking I/O will not be able to handle multiple connections in the same thread; each I/O operation on a socket will block the processing of any other connection. For this reason, the traditional approach to handle concurrency in web servers is to kick off a thread or a process (or to reuse one taken from a pool) for each concurrent connection that needs to be handled. This way, when a thread gets blocked for an I/O operation it will not impact the availability of the other requests, because they are handled in separate threads. The following image illustrates this scenario:
  • 23. Welcome to the Node.js platform [ 16 ] The preceding image lays emphasis on the amount of time each thread is idle, waiting for new data to be received from the associated connection. Now, if we also consider that any type of I/O can possibly block a request, for example, while interacting with databases or with the filesystem, we soon realize how many times a thread has to block in order to wait for the result of an I/O operation. Unfortunately, a thread is not cheap in terms of system resources, it consumes memory and causes context switches, so having a long running thread for each connection and not using it for most of the time, is not the best compromise in terms of efficiency. Non-blocking I/O In addition to blocking I/O, most modern operating systems support another mechanism to access resources, called non-blocking I/O. In this operating mode, the system call always returns immediately without waiting for the data to be read or written. If no results are available at the moment of the call, the function will simply return a predefined constant, indicating that there is no data available to return at that moment. For example, in Unix operating systems, the fcntl() function is used to manipulate an existing file descriptor to change its operating mode to non-blocking (with the O_NONBLOCK flag). Once the resource is in non-blocking mode, any read operation will fail with a return code, EAGAIN, in case the resource doesn't have any data ready to be read. The most basic pattern for accessing this kind of non-blocking I/O is to actively poll the resource within a loop until some actual data is returned; this is called busy-waiting. The following pseudocode shows you how it's possible to read from multiple resources using
  • 24. Welcome to the Node.js platform [ 17 ] non-blocking I/O and a polling loop: resources = [socketA, socketB, pipeA]; while(!resources.isEmpty()) { for(i = 0; i < resources.length; i++) { resource = resources[i]; //try to read var data = resource.read(); if(data === NO_DATA_AVAILABLE) //there is no data to read at the moment continue; if(data === RESOURCE_CLOSED) //the resource was closed, remove it from the list resources.remove(i); else //some data was received, process it consumeData(data); } } You can see that, with this simple technique, it is already possible to handle different resources in the same thread, but it's still not efficient. In fact, in the preceding example, the loop will consume precious CPU only for iterating over resources that are unavailable most of the time. Polling algorithms usually result in a huge amount of wasted CPU time. Event demultiplexing Busy-waiting is definitely not an ideal technique for processing non-blocking resources, but luckily, most modern operating systems provide a native mechanism to handle concurrent, non-blocking resources in an efficient way; this mechanism is called synchronous event demultiplexer or event notification interface. This component collects and queues I/O events that come from a set of watched resources, and block until new events are available to process. The following is the pseudocode of an algorithm that uses a generic synchronous event demultiplexer to read from two different resources: socketA, pipeB; watchedList.add(socketA, FOR_READ); //[1] watchedList.add(pipeB, FOR_READ); while(events = demultiplexer.watch(watchedList)) { //[2] //event loop foreach(event in events) { //[3] //This read will never block and will always return data data = event.resource.read(); if(data === RESOURCE_CLOSED) //the resource was closed, remove it from the watched list
  • 25. Welcome to the Node.js platform [ 18 ] demultiplexer.unwatch(event.resource); else //some actual data was received, process it consumeData(data); } } These are the important steps of the preceding pseudocode: The resources are added to a data structure, associating each one of them with a 1. specific operation, in our example a read. The event notifier is set up with the group of resources to be watched. This call is 2. synchronous and blocks until any of the watched resources is ready for a read. When this occurs, the event demultiplexer returns from the call and a new set of events is available to be processed. Each event returned by the event demultiplexer is processed. At this point, the 3. resource associated with each event is guaranteed to be ready to read and to not block during the operation. When all the events are processed, the flow will block again on the event demultiplexer until new events are again available to be processed. This is called the event loop. It's interesting to see that with this pattern, we can now handle several I/O operations inside a single thread, without using a busy-waiting technique. The following image shows us how a web server would be able to handle multiple connections using a synchronous event demultiplexer and a single thread: The previous image helps us understand how concurrency works in a single-threaded application using a synchronous event demultiplexer and non-blocking I/O. We can see
  • 26. Welcome to the Node.js platform [ 19 ] that using only one thread does not impair our ability to run multiple I/O bound tasks concurrently. The tasks are spread over time, instead of being spread across multiple threads. This has the clear advantage of minimizing the total idle time of the thread, as clearly shown in the image. This is not the only reason for choosing this model. To have only a single thread, in fact, also has a beneficial impact on the way programmers approach concurrency in general. Throughout the book, we will see how the absence of in-process race conditions and multiple threads to synchronize, allows us to use much simpler concurrency strategies. In the next chapter, we will have the opportunity to talk more about the concurrency model of Node.js. The reactor pattern We can now introduce the reactor pattern, which is a specialization of the algorithms presented in the previous section. The main idea behind it is to have a handler (which in Node.js is represented by a callback function) associated with each I/O operation, which will be invoked as soon as an event is produced and processed by the event loop. The structure of the reactor pattern is shown in the following image:
  • 27. Welcome to the Node.js platform [ 20 ] This is what happens in an application using the reactor pattern: The application generates a new I/O operation by submitting a request to the 1. Event Demultiplexer. The application also specifies a handler, which will be invoked when the operation completes. Submitting a new request to the Event Demultiplexer is a non-blocking call and it immediately returns the control back to the application. When a set of I/O operations completes, the Event Demultiplexer pushes the new 2. events into the Event Queue. At this point, the Event Loop iterates over the items of the Event Queue. 3. For each event, the associated handler is invoked. 4. The handler, which is part of the application code, will give back the control to 5. the Event Loop when its execution completes (5a). However, new asynchronous operations might be requested during the execution of the handler (5b), causing
  • 28. Welcome to the Node.js platform [ 21 ] new operations to be inserted in the Event Demultiplexer (1), before the control is given back to the Event Loop. When all the items in the Event Queue are processed, the loop will block again on 6. the Event Demultiplexer which will then trigger another cycle. The asynchronous behavior is now clear: the application expresses the interest to access a resource at one point in time (without blocking) and provides a handler, which will then be invoked at another point in time when the operation completes. A Node.js application will exit automatically when there are no more pending operations in the Event Demultiplexer, and no more events to be processed inside the Event Queue. We can now define the pattern at the heart of Node.js. Pattern (reactor): handles I/O by blocking until new events are available from a set of observed resources, and then reacting by dispatching each event to an associated handler. The non-blocking I/O engine of Node.js – libuv Each operating system has its own interface for the Event Demultiplexer: epoll on Linux, kqueue on Mac OS X, andI/O Completion Port API (IOCP) on Windows. Besides that, each I/O operation can behave quite differently depending on the type of the resource, even within the same OS. For example, in Unix, regular filesystem files do not support non- blocking operations, so, in order to simulate a non-blocking behavior, it is necessary to use a separate thread outside the Event Loop. All these inconsistencies across and within the different operating systems required a higher-level abstraction to be built for the Event Demultiplexer. This is exactly why the Node.js core team created a C library called libuv, with the objective to make Node.js compatible with all the major platforms and normalized the non-blocking behavior of the different types of resource; libuv today represents the low-level I/O engine of Node.js. Besides abstracting the underlying system calls, libuv also implements the reactor pattern, thus providing an API for creating event loops, managing the event queue, running asynchronous I/O operations, and queuing other types of tasks. A great resource to learn more about libuv is the free online book created by Nikhil Marathe, which is available at http://nikhilm.github.io/uvbook/
  • 29. Welcome to the Node.js platform [ 22 ] The recipe for Node.js The reactor pattern and libuv are the basic building blocks of Node.js, but we need the following three other components to build the full platform: A set of bindings responsible for wrapping and exposing libuv and other low- level functionality to JavaScript. V8, the JavaScript engine originally developed by Google for the Chrome browser. This is one of the reasons why Node.js is so fast and efficient. V8 is acclaimed for its revolutionary design, its speed, and for its efficient memory management. A core JavaScript library (called node-core) thatimplements the high-level Node.js API. Finally, this is the recipe of Node.js, and the following image represents its final architecture:
  • 30. Welcome to the Node.js platform [ 23 ] Summary In this chapter, we have seen how the Node.js platform is based on a few important principles that provide the foundation to build efficient and reusable code. The philosophy and the design choices behind the platform have, in fact, a strong influence on the structure and behavior of every application and module we create. Often, for a developer moving from another technology, these principles might seem unfamiliar and the usual instinctive
  • 31. Welcome to the Node.js platform [ 24 ] reaction is to fight the change by trying to find more familiar patterns inside a world which in reality requires a real shift in the mindset. On one hand, the asynchronous nature of the reactor pattern requires a different programming style made of callbacks and things that happen at a later time, without worrying too much about threads and race conditions. On the other hand, the module pattern and its principles of simplicity and minimalism creates interesting new scenarios in terms of reusability, maintenance, and usability. Finally, besides the obvious technical advantages of being fast, efficient, and based on JavaScript, Node.js is attracting so much interest because of the principles we have just discovered. For many, grasping the essence of this world feels like returning to the origins, to a more humane way of programming for both size and complexity and that's why developers end up falling in love with Node.js. The introduction of ES2015 makes things even more interesting and open new scenarios for being able to embrace all these advantages with an even more expressive syntax. In the next chapter, we will get into deep of the two basic asynchronous patterns used in Node.js: the callback pattern and the event emitter. We will also understand the difference between synchronous and asynchronous code and how to avoid to write unpredictable functions.
  • 32. 2 Node.js Essential Patterns Embracing the asynchronous nature of Node.js is not trivial at all, especially if coming from a language such as PHP where it is not usual to deal with asynchronous code. With synchronous programming we are used to imagine code as a series of consecutive computing steps defined to solve a specific problem. Every operation is blocking which means that only when an operation is completed it is possible to execute the next one. This approach makes the code easy to understand and debug. Instead, in asynchronous programming some operations like reading a file or performing a network request can be executed asynchronously in the background. When an asynchronous operation is performed, the next one is executed immediately, even if the previous (asynchronous) operation has not finished yet. The operations pending on the background can complete at any time and the whole application should be programmed to react in the proper way when an asynchronous finishes. While this non-blocking approach can guarantee superior performances compared to an always-blocking scenario, it provides a paradigm that is hard to picture in mind and that can get really cumbersome when dealing with more advanced applications that requires complex control flows. Node.js offers a series of tools and design patterns to deal optimally with asynchronous code and it's important to learn how to use them to gain confidence with asynchronous coding and write applications that are both performant and easy to understand and debug. In this chapter, we will see two of the most important asynchronous patterns: callback and event emitter. The callback pattern
  • 33. Random documents with unrelated content Scribd suggests to you:
  • 34. As mademoiselle de la Mole obstinately refused to look at him, Julien on the third day in spite of her evident objection, followed her into the billiard-room after dinner. “Well, sir, you think you have acquired some very strong rights over me?” she said to him with scarcely controlled anger, “since you venture to speak to me, in spite of my very clearly manifested wish? Do you know that no one in the world has had such effrontery?” The dialogue of these two lovers was incomparably humourous. Without suspecting it, they were animated by mutual sentiments of the most vivid hate. As neither the one nor the other had a meekly patient character, while they were both disciples of good form, they soon came to informing each other quite clearly that they would break for ever. “I swear eternal secrecy to you,” said Julien. “I should like to add that I would never address a single word to you, were it not that a marked change might perhaps jeopardise your reputation.” He saluted respectfully and left. He accomplished easily enough what he believed to be a duty; he was very far from thinking himself much in love with mademoiselle de la Mole. He had certainly not loved her three days before, when he had been hidden in the big mahogany cupboard. But the moment that he found himself estranged from her for ever his mood underwent a complete and rapid change. His memory tortured him by going over the least details in that night, which had as a matter of fact left him so cold. In the very night that followed this announcement of a final rupture, Julien almost went mad at being obliged to own to himself that he loved mademoiselle de la Mole. This discovery was followed by awful struggles: all his emotions were overwhelmed. Two days later, instead of being haughty towards M. de Croisenois, he could have almost burst out into tears and embraced him. His habituation to unhappiness gave him a gleam of commonsense, he decided to leave for Languedoc, packed his trunk
  • 35. and went to the post. He felt he would faint, when on arriving at the office of the mails, he was told that by a singular chance there was a place in the Toulouse mail. He booked it and returned to the Hôtel de la Mole to announce his departure to the marquis. M. de la Mole had gone out. More dead than alive Julien went into the library to wait for him. What was his emotion when he found mademoiselle de la Mole there. As she saw him come, she assumed a malicious expression which it was impossible to mistake. In his unhappiness and surprise Julien lost his head and was weak enough to say to her in a tone of the most heartfelt tenderness. “So you love me no more.” “I am horrified at having given myself to the first man who came along,” said Mathilde crying with rage against herself. “The first man who came along,” cried Julien, and he made for an old mediæval sword which was kept in the library as a curiosity. His grief—which he thought was at its maximum at the moment when he had spoken to mademoiselle de la Mole—had been rendered a hundred times more intense by the tears of shame which he saw her shedding. He would have been the happiest of men if he had been able to kill her. When he was on the point of drawing the sword with some difficulty from its ancient scabbard, Mathilde, rendered happy by so novel a sensation, advanced proudly towards him, her tears were dry. The thought of his benefactor—the marquis de la Mole—presented itself vividly to Julien. “Shall I kill his daughter?” he said to himself, “how horrible.” He made a movement to throw down the sword. “She will certainly,” he thought, “burst out laughing at the sight of such a melodramatic pose:” that idea was responsible for his regaining all his self-possession. He looked curiously at the blade of
  • 36. the old sword as though he had been looking for some spot of rust, then put it back in the scabbard and replaced it with the utmost tranquillity on the gilt bronze nail from which it hung. The whole manœuvre, which towards the end was very slow, lasted quite a minute; mademoiselle de la Mole looked at him in astonishment. “So I have been on the verge of being killed by my lover,” she said to herself. This idea transported her into the palmiest days of the age of Charles IX. and of Henri III. She stood motionless before Julien, who had just replaced the sword; she looked at him with eyes whose hatred had disappeared. It must be owned that she was very fascinating at this moment, certainly no woman looked less like a Parisian doll (this expression symbolised Julien’s great objection to the women of this city). “I shall relapse into some weakness for him,” thought Mathilde; “it is quite likely that he will think himself my lord and master after a relapse like that at the very moment that I have been talking to him so firmly.” She ran away. “By heaven, she is pretty said Julien as he watched her run and that’s the creature who threw herself into my arms with so much passion scarcely a week ago ... and to think that those moments will never come back? And that it’s my fault, to think of my being lacking in appreciation at the very moment when I was doing something so extraordinarily interesting! I must own that I was born with a very dull and unfortunate character.” The marquis appeared; Julien hastened to announce his departure. “Where to?” said M. de la Mole. “For Languedoc.” “No, if you please, you are reserved for higher destinies. If you leave it will be for the North.... In military phraseology I actually confine you in the hotel. You will compel me to be never more than two or three hours away. I may have need of you at any moment.”
  • 37. Julien bowed and retired without a word, leaving the marquis in a state of great astonishment. He was incapable of speaking. He shut himself up in his room. He was there free to exaggerate to himself all the awfulness of his fate. “So,” he thought, “I cannot even get away. God knows how many days the marquis will keep me in Paris. Great God, what will become of me, and not a friend whom I can consult? The abbé Pirard will never let me finish my first sentence, while the comte Altamira will propose enlisting me in some conspiracy. And yet I am mad; I feel it, I am mad. Who will be able to guide me, what will become of me?” CHAPTER XLVIII CRUEL MOMENTS And she confesses it to me! She goes into even the smallest details! Her beautiful eyes fixed on mine, and describes the love which she felt for another.—Schiller. The delighted mademoiselle de la Mole thought of nothing but the happiness of having been nearly killed. She went so far as to say to herself, “he is worthy of being my master since he was on the point of killing me. How many handsome young society men would have to be melted together before they were capable of so passionate a transport.” “I must admit that he was very handsome at the time when he climbed up on the chair to replace the sword in the same picturesque position in which the decorator hung it! After all it was not so foolish of me to love him.”
  • 38. If at that moment some honourable means of reconciliation had presented itself, she would have embraced it with pleasure. Julien locked in his room was a prey to the most violent despair. He thought in his madness of throwing himself at her feet. If instead of hiding himself in an out of the way place, he had wandered about the garden of the hôtel so as to keep within reach of any opportunity, he would perhaps have changed in a single moment his awful unhappiness into the keenest happiness. But the tact for whose lack we are now reproaching him would have been incompatible with that sublime seizure of the sword, which at the present time rendered him so handsome in the eyes of mademoiselle de la Mole. This whim in Julien’s favour lasted the whole day; Mathilde conjured up a charming image of the short moments during which she had loved him: she regretted them. “As a matter of fact,” she said to herself, “my passion for this poor boy can from his point of view only have lasted from one hour after midnight when I saw him arrive by his ladder with all his pistols in his coat pocket, till eight o’clock in the morning. It was a quarter of an hour after that as I listened to mass at Sainte-Valère that I began to think that he might very well try to terrify me into obedience.” After dinner mademoiselle de la Mole, so far from avoiding Julien, spoke to him and made him promise to follow her into the garden. He obeyed. It was a new experience. Without suspecting it Mathilde was yielding to the love which she was now feeling for him again. She found an extreme pleasure in walking by his side, and she looked curiously at those hands which had seized the sword to kill her that very morning. After such an action, after all that had taken place, some of the former conversation was out of the question. Mathilde gradually began to talk confidentially to him about the state of her heart. She found a singular pleasure in this kind of conversation, she even went so far as to describe to him the fleeting moments of enthusiasm which she had experienced for M. de Croisenois, for M. de Caylus——
  • 39. “What! M. de Caylus as well!” exclaimed Julien, and all the jealousy of a discarded lover burst out in those words, Mathilde thought as much, but did not feel at all insulted. She continued torturing Julien by describing her former sentiments with the most picturesque detail and the accent of the most intimate truth. He saw that she was portraying what she had in her mind’s eye. He had the pain of noticing that as she spoke she made new discoveries in her own heart. The unhappiness of jealousy could not be carried further. It is cruel enough to suspect that a rival is loved, but there is no doubt that to hear the woman one adores confess in detail the love which rivals inspires, is the utmost limit of anguish. Oh, how great a punishment was there now for those impulses of pride which had induced Julien to place himself as superior to the Caylus and the Croisenois! How deeply did he feel his own unhappiness as he exaggerated to himself their most petty advantages. With what hearty good faith he despised himself. Mathilde struck him as adorable. All words are weak to express his excessive admiration. As he walked beside her he looked surreptitiously at her hands, her arms, her queenly bearing. He was so completely overcome by love and unhappiness as to be on the point of falling at her feet and crying “pity.” “Yes, and that person who is so beautiful, who is so superior to everything and who loved me once, will doubtless soon love M. de Caylus.” Julien could have no doubts of mademoiselle de la Mole’s sincerity, the accent of truth was only too palpable in everything she said. In order that nothing might be wanting to complete his unhappiness there were moments when, as a result of thinking about the sentiments which she had once experienced for M. de Caylus, Mathilde came to talk of him, as though she loved him at the present time. She certainly put an inflection of love into her voice. Julien distinguished it clearly.
  • 40. He would have suffered less if his bosom had been filled inside with molten lead. Plunged as he was in this abyss of unhappiness how could the poor boy have guessed that it was simply because she was talking to him, that mademoiselle de la Mole found so much pleasure in recalling those weaknesses of love which she had formerly experienced for M. de Caylus or M. de Luz. Words fail to express Julien’s anguish. He listened to these detailed confidences of the love she had experienced for others in that very avenue of pines where he had waited so few days ago for one o’clock to strike that he might invade her room. No human being can undergo a greater degree of unhappiness. This kind of familiar cruelty lasted for eight long days. Mathilde sometimes seemed to seek opportunities of speaking to him and sometimes not to avoid them; and the one topic of conversation to which they both seemed to revert with a kind of cruel pleasure, was the description of the sentiments she had felt for others. She told him about the letters which she had written, she remembered their very words, she recited whole sentences by heart. She seemed during these last days to be envisaging Julien with a kind of malicious joy. She found a keen enjoyment in his pangs. One sees that Julien had no experience of life; he had not even read any novels. If he had been a little less awkward and he had coolly said to the young girl, whom he adored so much and who had been giving him such strange confidences: “admit that though I am not worth as much as all these gentlemen, I am none the less the man whom you loved,” she would perhaps have been happy at being at thus guessed; at any rate success would have entirely depended on the grace with which Julien had expressed the idea, and on the moment which he had chosen to do so. In any case he would have extricated himself well and advantageously from a situation which Mathilde was beginning to find monotonous. “And you love me no longer, me, who adores you!” said Julien to her one day, overcome by love and unhappiness. This piece of folly was perhaps the greatest which he could have committed. These
  • 41. words immediately destroyed all the pleasure which mademoiselle de la Mole found in talking to him about the state of her heart. She was beginning to be surprised that he did not, after what had happened, take offence at what she told him. She had even gone so far as to imagine at the very moment when he made that foolish remark that perhaps he did not love her any more. “His pride has doubtless extinguished his love,” she was saying to herself. “He is not the man to sit still and see people like Caylus, de Luz, Croisenois whom he admits are so superior, preferred to him. No, I shall never see him at my feet again.” Julien had often in the naivety of his unhappiness, during the previous days praised sincerely the brilliant qualities of these gentlemen; he would even go so far as to exaggerate them. This nuance had not escaped mademoiselle de la Mole, she was astonished by it, but did not guess its reason. Julien’s frenzied soul, in praising a rival whom he thought was loved, was sympathising with his happiness. These frank but stupid words changed everything in a single moment; confident that she was loved, Mathilde despised him utterly. She was walking with him when he made his ill-timed remark; she left him, and her parting look expressed the most awful contempt. She returned to the salon and did not look at him again during the whole evening. This contempt monopolised her mind the following day. The impulse which during the last week had made her find so much pleasure in treating Julien as her most intimate friend was out of the question; the very sight of him was disagreeable. The sensation Mathilde felt reached the point of disgust; nothing can express the extreme contempt which she experienced when her eyes fell upon him. Julien had understood nothing of the history of Mathilde’s heart during the last week, but he distinguished the contempt. He had the good sense only to appear before her on the rarest possible occasions, and never looked at her.
  • 42. But it was not without a mortal anguish that he, as it were, deprived himself of her presence. He thought he felt his unhappiness increasing still further. “The courage of a man’s heart cannot be carried further,” he said to himself. He passed his life seated at a little window at the top of the hôtel; the blind was carefully closed, and from here at any rate he could see mademoiselle de la Mole when she appeared in the garden. What were his emotions when he saw her walking after dinner with M. de Caylus, M. de Luz, or some other for whom she had confessed to him some former amorous weakness! Julien had no idea that unhappiness could be so intense; he was on the point of shouting out. This firm soul was at last completely overwhelmed. Thinking about anything else except mademoiselle de la Mole had become odious to him; he became incapable of writing the simplest letters. “You are mad,” the marquis said to him. Julien was frightened that his secret might be guessed, talked about illness and succeeded in being believed. Fortunately for him the marquis rallied him at dinner about his next journey; Mathilde understood that it might be a very long one. It was now several days that Julien had avoided her, and the brilliant young men who had all that this pale sombre being she had once loved was lacking, had no longer the power of drawing her out of her reverie. “An ordinary girl,” she said to herself, “would have sought out the man she preferred among those young people who are the cynosure of a salon; but one of the characteristics of genius is not to drive its thoughts over the rut traced by the vulgar. “Why, if I were the companion of a man like Julien, who only lacks the fortune that I possess, I should be continually exciting attention, I should not pass through life unnoticed. Far from incessantly fearing a revolution like my cousins who are so frightened of the people that they have not the pluck to scold a postillion who drives them badly, I should be certain of playing a rôle and a great rôle, for the man
  • 43. whom I have chosen has a character and a boundless ambition. What does he lack? Friends, money? I will give them him.” But she treated Julien in her thought as an inferior being whose love one could win whenever one wanted. CHAPTER XLIX THE OPERA BOUFFE How the spring of love resembleth The uncertain glory of an April day, Which now shows all the beauty of the sun, And by and by a cloud takes all away.— Shakespeare. Engrossed by thoughts of her future and the singular rôle which she hoped to play, Mathilde soon came to miss the dry metaphysical conversations which she had often had with Julien. Fatigued by these lofty thoughts she would sometimes also miss those moments of happiness which she had found by his side; these last memories were not unattended by remorse which at certain times even overwhelmed her. “But one may have a weakness,” she said to herself, “a girl like I am should only forget herself for a man of real merit; they will not say that it is his pretty moustache or his skill in horsemanship which have fascinated me, but rather his deep discussions on the future of France and his ideas on the analogy between the events which are going to burst upon us and the English revolution of 1688.” “I have been seduced,” she answered in her remorse. “I am a weak woman, but at least I have not been led astray like a doll by
  • 44. exterior advantages.” “If there is a revolution why should not Julien Sorel play the rôle of Roland and I the rôle of Madame Roland? I prefer that part to Madame de Stael’s; the immorality of my conduct will constitute an obstacle in this age of ours. I will certainly not let them reproach me with an act of weakness; I should die of shame.” Mathilde’s reveries were not all as grave, one must admit, as the thoughts which we have just transcribed. She would look at Julien and find a charming grace in his slightest action. “I have doubtless,” she would say, “succeeded in destroying in him the very faintest idea he had of any one else’s rights.” “The air of unhappiness and deep passion with which the poor boy declared his love to me eight days ago proves it; I must own it was very extraordinary of me to manifest anger at words in which there shone so much respect and so much of passion. Am I not his real wife? Those words of his were quite natural, and I must admit, were really very nice. Julien still continued to love me, even after those eternal conversations in which I had only spoken to him (cruelly enough I admit), about those weaknesses of love which the boredom of the life I lead had inspired me for those young society men of whom he is so jealous. Ah, if he only knew what little danger I have to fear from them; how withered and stereotyped they seem to me in comparison with him.” While indulging in these reflections Mathilde made a random pencil sketch of a profile on a page of her album. One of the profiles she had just finished surprised and delighted her. It had a striking resemblance to Julien. “It is the voice of heaven. That’s one of the miracles of love,” she cried ecstatically; “Without suspecting it, I have drawn his portrait.” She fled to her room, shut herself up in it, and with much application made strenuous endeavours to draw Julien’s portrait, but she was unable to succeed; the profile she had traced at random still
  • 45. remained the most like him. Mathilde was delighted with it. She saw in it a palpable proof of the grand passion. She only left her album very late when the marquise had her called to go to the Italian Opera. Her one idea was to catch sight of Julien, so that she might get her mother to request him to keep them company. He did not appear, and the ladies had only ordinary vulgar creatures in their box. During the first act of the opera, Mathilde dreamt of the man she loved with all the ecstasies of the most vivid passion; but a love-maxim in the second act sung it must be owned to a melody worthy of Cimarosa pierced her heart. The heroine of the opera said “You must punish me for the excessive adoration which I feel for him. I love him too much.” From the moment that Mathilde heard this sublime song everything in the world ceased to exist. She was spoken to, she did not answer; her mother reprimanded her, she could scarcely bring herself to look at her. Her ecstasy reached a state of exultation and passion analogous to the most violent transports which Julien had felt for her for some days. The divinely graceful melody to which the maxim, which seemed to have such a striking application to her own position, was sung, engrossed all the minutes when she was not actually thinking of Julien. Thanks to her love for music she was on this particular evening like madame de Rênal always was, when she thought of Julien. Love of the head has doubtless more intelligence than true love, but it only has moments of enthusiasm. It knows itself too well, it sits in judgment on itself incessantly; far from distracting thought it is made by sheer force of thought. On returning home Mathilde, in spite of madame de la Mole’s remonstrances, pretended to have a fever and spent a part of the night in going over this melody on her piano. She sang the words of the celebrated air which had so fascinated her:— Devo punirmi, devo punirmi. Se troppo amai, etc.
  • 46. As the result of this night of madness, she imagined that she had succeeded in triumphing over her love. This page will be prejudicial in more than one way to the unfortunate author. Frigid souls will accuse him of indecency. But the young ladies who shine in the Paris salons have no right to feel insulted at the supposition that one of their number might be liable to those transports of madness which have been degrading the character of Mathilde. That character is purely imaginary, and is even drawn quite differently from that social code which will guarantee so distinguished a place in the world’s history to nineteenth century civilization. The young girls who have adorned this winter’s balls are certainly not lacking in prudence. I do not think either that they can be accused of being unduly scornful of a brilliant fortune, horses, fine estates and all the guarantees of a pleasant position in society. Far from finding these advantages simply equivalent to boredom, they usually concentrate on them their most constant desires and devote to them such passion as their hearts possess. Nor again is it love which is the dominant principle in the career of young men who, like Julien, are gifted with some talent; they attach themselves with an irresistible grip to some côterie, and when the côterie succeeds all the good things of society are rained upon them. Woe to the studious man who belongs to no côterie, even his smallest and most doubtful successes will constitute a grievance, and lofty virtue will rob him and triumph. Yes, monsieur, a novel is a mirror which goes out on a highway. Sometimes it reflects the azure of the heavens, sometimes the mire of the pools of mud on the way, and the man who carries this mirror in his knapsack is forsooth to be accused by you of being immoral! His mirror shows the mire, and you accuse the mirror! Rather accuse the main road where the mud is, or rather the inspector of roads who allows the water to accumulate and the mud to form. Now that it is quite understood that Mathilde’s character is impossible in our own age, which is as discreet as it is virtuous, I am
  • 47. less frightened of offence by continuing the history of the follies of this charming girl. During the whole of the following day she looked out for opportunities of convincing herself of her triumph over her mad passion. Her great aim was to displease Julien in everything; but not one of his movements escaped her. Julien was too unhappy, and above all too agitated to appreciate so complicated a stratagem of passion. Still less was he capable of seeing how favourable it really was to him. He was duped by it. His unhappiness had perhaps never been so extreme. His actions were so little controlled by his intellect that if some mournful philosopher had said to him, “Think how to exploit as quickly as you can those symptoms which promise to be favourable to you. In this kind of head-love which is seen at Paris, the same mood cannot last more than two days,” he would not have understood him. But however ecstatic he might feel, Julien was a man of honour. Discretion was his first duty. He appreciated it. Asking advice, describing his agony to the first man who came along would have constituted a happiness analogous to that of the unhappy man who, when traversing a burning desert receives from heaven a drop of icy water. He realised the danger, was frightened of answering an indiscreet question by a torrent of tears, and shut himself up in his own room. He saw Mathilde walking in the garden for a long time. When she at last left it, he went down there and approached the rose bush from which she had taken a flower. The night was dark and he could abandon himself to his unhappiness without fear of being seen. It was obvious to him that mademoiselle de la Mole loved one of those young officers with whom she had chatted so gaily. She had loved him, but she had realised his little merit, “and as a matter of fact I had very little,” Julien said to himself with full conviction. “Taking me all round I am a very dull, vulgar person, very boring to others and quite unbearable to myself.” He was mortally disgusted with all his good qualities, and with all the things which he had once loved so enthusiastically; and it was when his imagination was in this
  • 48. distorted condition that he undertook to judge life by means of its aid. This mistake is typical of a superior man. The idea of suicide presented itself to him several times; the idea was full of charm, and like a delicious rest; because it was the glass of iced water offered to the wretch dying of thirst and heat in the desert. “My death will increase the contempt she has for me,” he exclaimed. “What a memory I should leave her.” Courage is the only resource of a human being who has fallen into this last abyss of unhappiness. Julien did not have sufficient genius to say to himself, “I must dare,” but as he looked at the window of Mathilde’s room he saw through the blinds that she was putting out her light. He conjured up that charming room which he had seen, alas! once in his whole life. His imagination did not go any further. One o’clock struck. Hearing the stroke of the clock and saying to himself, “I will climb up the ladder,” scarcely took a moment. It was the flash of genius, good reasons crowded on his mind. “May I be more fortunate than before,” he said to himself. He ran to the ladder. The gardener had chained it up. With the help of the cock of one of his little pistols which he broke, Julien, who for the time being was animated by a superhuman force, twisted one of the links of the chain which held the ladder. He was master of it in a few minutes, and placed it against Mathilde’s window. “She will be angry and riddle me with scornful words! What does it matter? I will give her a kiss, one last kiss. I will go up to my room and kill myself ... my lips will touch her cheek before I die.” He flew up the ladder and knocked at the blind; Mathilde heard him after some minutes and tried to open the blind but the ladder was in the way. Julien hung to the iron hook intending to keep the blind open, and at the imminent risk of falling down, gave the ladder a violent shake which moved it a little. Mathilde was able to open the blind. He threw himself into the window more dead than alive. “So it is you, dear,” she said as she rushed into his arms.
  • 49. The excess of Julien’s happiness was indescribable. Mathilde’s almost equalled his own. She talked against herself to him and denounced herself. “Punish me for my awful pride,” she said to him, clasping him in her arms so tightly as almost to choke him. “You are my master, dear, I am your slave. I must ask your pardon on my knees for having tried to rebel.” She left his arms to fall at his feet. “Yes,” she said to him, still intoxicated with happiness and with love, “you are my master, reign over me for ever. When your slave tries to revolt, punish her severely.” In another moment she tore herself from his arms, and lit a candle, and it was only by a supreme effort that Julien could prevent her from cutting off a whole tress of her hair. “I want to remind myself,” she said to him, “that I am your handmaid. If I am ever led astray again by my abominable pride, show me this hair and say, ‘It is not a question of the emotion which your soul may be feeling at present, you have sworn to obey, obey on your honour.’” But it is wiser to suppress the description of so intense a transport of delirious happiness. Julien’s unselfishness was equal to his happiness. “I must go down by the ladder,” he said to Mathilde, when he saw the dawn of day appear from the quarter of the east over the distant chimneys beyond the garden. “The sacrifice that I impose on myself is worthy of you. I deprive myself of some hours of the most astonishing happiness that a human soul can savour, but it is a sacrifice I make for the sake of your reputation. If you know my heart you will appreciate how violent is the strain to which I am putting myself. Will you always be to me what you are now? But honour speaks, it suffices. Let me tell you that since our last interview, thieves have not been the only object of suspicion. M. de la Mole has set a guard
  • 50. in the garden. M. Croisenois is surrounded by spies: they know what he does every night.” Mathilde burst out laughing at this idea. Her mother and a chamber-maid were woken up, they suddenly began to speak to her through the door. Julien looked at her, she grew pale as she scolded the chamber-maid, and she did not deign to speak to her mother. “But suppose they think of opening the window, they will see the ladder,” Julien said to her.
  • 51. He clasped her again in his arms, rushed on to the ladder, and slid, rather than climbed down; he was on the ground in a moment. Three seconds after the ladder was in the avenue of pines, and Mathilde’s honour was saved. Julien returned to his room and found that he was bleeding and almost naked. He had wounded himself in sliding down in that dare-devil way. Extreme happiness had made him regain all the energy of his character. If twenty men had presented themselves it would have proved at this moment only an additional pleasure to have attacked them unaided. Happily his military prowess was not put to the proof. He laid the ladder in its usual place and replaced the chain which held it. He did not forget to efface the mark which the ladder had left on the bed of exotic flowers under Mathilde’s window. As he was moving his hand over the soft ground in the darkness and satisfying himself that the mark had entirely disappeared, he felt something fall down on his hands. It was a whole tress of Mathilde’s hair which she had cut off and thrown down to him. She was at the window. “That’s what your servant sends you,” she said to him in a fairly loud voice, “It is the sign of eternal gratitude. I renounce the exercise of my reason, be my master.” Julien was quite overcome and was on the point of going to fetch the ladder again and climbing back into her room. Finally reason prevailed. Getting back into the hôtel from the garden was not easy. He succeeded in forcing the door of a cellar. Once in the house he was obliged to break through the door of his room as silently as possible. In his agitation he had left in the little room which he had just abandoned so rapidly, the key which was in the pocket of his coat. “I only hope she thinks of hiding that fatal trophy,” he thought. Finally fatigue prevailed over happiness, and as the sun was rising he fell into a deep sleep.
  • 52. The breakfast bell only just managed to wake him up. He appeared in the dining-room. Shortly afterwards Mathilde came in. Julien’s pride felt deliciously flattered as he saw the love which shone in the eyes of this beautiful creature who was surrounded by so much homage; but soon his discretion had occasion to be alarmed. Making an excuse of the little time that she had had to do her hair, Mathilde had arranged it in such a way that Julien could see at the first glance the full extent of the sacrifice that she had made for his sake, by cutting off her hair on the previous night. If it had been possible to spoil so beautiful a face by anything whatsoever, Mathilde would have succeeded in doing it. A whole tress of her beautiful blonde hair was cut off to within half an inch of the scalp. Mathilde’s whole manner during breakfast was in keeping with this initial imprudence. One might have said that she had made a specific point of trying to inform the whole world of her mad passion for Julien. Happily on this particular day M. de la Mole and the marquis were very much concerned about an approaching bestowal of “blue ribbons” which was going to take place, and in which M. de Chaulnes was not comprised. Towards the end of the meal, Mathilde, who was talking to Julien, happened to call him “My Master.” He blushed up to the whites of his eyes. Mathilde was not left alone for an instant that day, whether by chance or the deliberate policy of madame de la Mole. In the evening when she passed from the dining-room into the salon, however, she managed to say to Julien: “You may be thinking I am making an excuse, but mamma has just decided that one of her women is to spend the night in my room.” This day passed with lightning rapidity. Julien was at the zenith of happiness. At seven o’clock in the morning of the following day he installed himself in the library. He hoped the mademoiselle de la Mole would deign to appear there; he had written her an interminable letter. He only saw her several hours afterwards at breakfast. Her hair was done to-day with the very greatest care; a
  • 53. marvellous art had managed to hide the place where the hair had been cut. She looked at Julien once or twice, but her eyes were polite and calm, and there was no question of calling him “My Master.” Julien’s astonishment prevented him from breathing—Mathilde was reproaching herself for all she had done for him. After mature reflection, she had come to the conclusion that he was a person who, though not absolutely commonplace, was yet not sufficiently different from the common ruck to deserve all the strange follies that she had ventured for his sake. To sum up she did not give love a single thought; on this particular day she was tired of loving. As for Julien, his emotions were those of a child of sixteen. He was a successive prey to awful doubt, astonishment and despair during this breakfast which he thought would never end. As soon as he could decently get up from the table, he flew rather than ran to the stable, saddled his horse himself, and galloped off. “I must kill my heart through sheer force of physical fatigue,” he said to himself as he galloped through the Meudon woods. “What have I done, what have I said to deserve a disgrace like this?” “I must do nothing and say nothing to-day,” he thought as he re- entered the hôtel. “I must be as dead physically as I am morally.” Julien saw nothing any more, it was only his corpse which kept moving. CHAPTER L THE JAPANESE VASE His heart does not first realise the full extremity of his unhappiness: he is more troubled than moved. But as reason returns he feels the depth of his misfortune. All the pleasures of
  • 54. life seem to have been destroyed, he can only feel the sharp barbs of a lacerating despair. But what is the use of talking of physical pain? What pain which is only felt by the body can be compared to this pain?—Jean Paul. The dinner bell rang, Julien had barely time to dress: he found Mathilde in the salon. She was pressing her brother and M. de Croisenois to promise her that they would not go and spend the evening at Suresnes with madame the maréchale de Fervaques. It would have been difficult to have shown herself more amiable or fascinating to them. M. de Luz, de Caylus and several of their friends came in after dinner. One would have said that mademoiselle de la Mole had commenced again to cultivate the most scrupulous conventionality at the same time as her sisterly affection. Although the weather was delightful this evening, she refused to go out into the garden, and insisted on their all staying near the arm-chair where madame de la Mole was sitting. The blue sofa was the centre of the group as it had been in the winter. Mathilde was out of temper with the garden, or at any rate she found it absolutely boring: it was bound up with the memory of Julien. Unhappiness blunts the edge of the intellect. Our hero had the bad taste to stop by that little straw chair which had formerly witnessed his most brilliant triumphs. To-day none spoke to him, his presence seemed to be unnoticed, and worse than that. Those of mademoiselle de la Mole’s friends who were sitting near him at the end of the sofa, made a point of somehow or other turning their back on him, at any rate he thought so. “It is a court disgrace,” he thought. He tried to study for a moment the people who were endeavouring to overwhelm him with their contempt. M. de Luz had an important post in the King’s suite, the result of which was that the handsome officer began every conversation with every listener who came along by telling him this special piece of information. His uncle had started at seven o’clock
  • 55. for St. Cloud and reckoned on spending the night there. This detail was introduced with all the appearance of good nature but it never failed to be worked in. As Julien scrutinized M. de Croisenois with a stern gaze of unhappiness, he observed that this good amiable young man attributed a great influence to occult causes. He even went so far as to become melancholy and out of temper if he saw an event of the slightest importance ascribed to a simple and perfectly natural cause. “There is an element of madness in this,” Julien said to himself. This man’s character has a striking analogy with that of the Emperor Alexander, such as the Prince Korasoff described it to me. During the first year of his stay in Paris poor Julien, fresh from the seminary and dazzled by the graces of all these amiable young people, whom he found so novel, had felt bound to admire them. Their true character was only beginning to become outlined in his eyes. “I am playing an undignified rôle here,” he suddenly thought. The question was, how he could leave the little straw chair without undue awkwardness. He wanted to invent something, and tried to extract some novel excuse from an imagination which was otherwise engrossed. He was compelled to fall back on his memory, which was, it must be owned, somewhat poor in resources of this kind. The poor boy was still very much out of his element, and could not have exhibited a more complete and noticeable awkwardness when he got up to leave the salon. His misery was only too palpable in his whole manner. He had been playing, for the last three quarters of an hour, the rôle of an officious inferior from whom one does not take the trouble to hide what one really thinks. The critical observations he had just made on his rivals prevented him, however, from taking his own unhappiness too tragically. His pride could take support in what had taken place the previous day. “Whatever may be their advantages over me,” he thought, as he went into the garden alone, “Mathilde has never been to a single one of them what, twice in my life, she has deigned to be to me!” His penetration did not go further. He absolutely failed to appreciate
  • 56. the character of the extraordinary person whom chance had just made the supreme mistress of all his happiness. He tried, on the following day, to make himself and his horse dead tired with fatigue. He made no attempt in the evening to go near the blue sofa to which Mathilde remained constant. He noticed that comte Norbert did not even deign to look at him when he met him about the house. “He must be doing something very much against the grain,” he thought; “he is naturally so polite.” Sleep would have been a happiness to Julien. In spite of his physical fatigue, memories which were only too seductive commenced to invade his imagination. He had not the genius to see that, inasmuch as his long rides on horseback over forests on the outskirts of Paris only affected him, and had no affect at all on Mathilde’s heart or mind, he was consequently leaving his eventual destiny to the caprice of chance. He thought that one thing would give his pain an infinite relief: it would be to speak to Mathilde. Yet what would he venture to say to her? He was dreaming deeply about this at seven o’clock one morning when he suddenly saw her enter the library. “I know, monsieur, that you are anxious to speak to me.” “Great heavens! who told you?” “I know, anyway; that is enough. If you are dishonourable, you can ruin me, or at least try to. But this danger, which I do not believe to be real, will certainly not prevent me from being sincere. I do not love you any more, monsieur, I have been led astray by my foolish imagination.” Distracted by love and unhappiness, as a result of this terrible blow, Julien tried to justify himself. Nothing could have been more absurd. Does one make any excuses for failure to please? But reason had no longer any control over his actions. A blind instinct urged him to get the determination of his fate postponed. He thought that, so long as he kept on speaking, all could not be over. Mathilde had not listened to his words; their sound irritated her. She could not conceive how he could have the audacity to interrupt her.
  • 57. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! textbookfull.com