100% found this document useful (1 vote)
132 views

Node js in Practice 1st Edition Alex R. Young instant download

Node.js in Practice is a comprehensive guide that covers the fundamentals of Node.js, real-world applications, and module writing. The book includes 115 techniques and is structured into three parts: Node Fundamentals, Real-World Recipes, and Writing Modules. It aims to help developers build scalable JavaScript applications effectively.

Uploaded by

isherhodorl2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
132 views

Node js in Practice 1st Edition Alex R. Young instant download

Node.js in Practice is a comprehensive guide that covers the fundamentals of Node.js, real-world applications, and module writing. The book includes 115 techniques and is structured into three parts: Node Fundamentals, Real-World Recipes, and Writing Modules. It aims to help developers build scalable JavaScript applications effectively.

Uploaded by

isherhodorl2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Node js in Practice 1st Edition Alex R.

Young
download

https://ebookname.com/product/node-js-in-practice-1st-edition-
alex-r-young/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Node js Blueprints Tsonev

https://ebookname.com/product/node-js-blueprints-tsonev/

Node js By Example 1st Edition Tsonev

https://ebookname.com/product/node-js-by-example-1st-edition-
tsonev/

Professional Node js building JavaScript based scalable


software 1st Edition Pedro Teixeira

https://ebookname.com/product/professional-node-js-building-
javascript-based-scalable-software-1st-edition-pedro-teixeira/

Intermediate Algebra Art of Problem Solving First


Edition Richard Rusczyk

https://ebookname.com/product/intermediate-algebra-art-of-
problem-solving-first-edition-richard-rusczyk/
Media Materiality and Memory Grounding the Groove 1st
Edition Elodie A. Roy

https://ebookname.com/product/media-materiality-and-memory-
grounding-the-groove-1st-edition-elodie-a-roy/

A Strong and Steady Pulse Stories from a Cardiologist


1st Edition Gregory D. Chapman

https://ebookname.com/product/a-strong-and-steady-pulse-stories-
from-a-cardiologist-1st-edition-gregory-d-chapman/

Saving Migrant Birds Developing Strategies for the


Future Corrie Herring Hooks Series 1st Edition John
Faaborg

https://ebookname.com/product/saving-migrant-birds-developing-
strategies-for-the-future-corrie-herring-hooks-series-1st-
edition-john-faaborg/

Coaching Positively Lessons for Coaches from Positive


Psychology 1st Edition Matt Driver

https://ebookname.com/product/coaching-positively-lessons-for-
coaches-from-positive-psychology-1st-edition-matt-driver/

IT architectures and middleware strategies for building


large integrated systems 2. ed., 4. print Edition
Britton

https://ebookname.com/product/it-architectures-and-middleware-
strategies-for-building-large-integrated-systems-2-ed-4-print-
edition-britton/
An Atlas of Endometriosis 3rd Edition Caroline Overton

https://ebookname.com/product/an-atlas-of-endometriosis-3rd-
edition-caroline-overton/
Alex Young
Marc Harter
FOREWORD BY
Ben Noordhuis

INCLUDES 115 TECHNIQUES

MANNING
Node.js in Practice

ALEX YOUNG
MARC HARTER

MANNING
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: [email protected]

©2015 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in


any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.

Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15 percent recycled and processed without the use of elemental
chlorine.

Manning Publications Co. Development editor: Cynthia Kane


20 Baldwin Road Technical development editor: Jose Maria Alvarez Rodriguez
PO Box 761 Copyeditor: Benjamin Berg
Shelter Island, NY 11964 Proofreader: Katie Tennant
Typesetter: Gordan Salinovic
Cover designer: Marija Tudor

ISBN 9781617290930
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 19 18 17 16 15 14
brief contents
PART 1 NODE FUNDAMENTALS .......................................................1
1 ■ Getting started 3
2 ■ Globals: Node’s environment 15
3 ■ Buffers: Working with bits, bytes, and encodings 39
4 ■ Events: Mastering EventEmitter and beyond 64
5 ■ Streams: Node’s most powerful and misunderstood
feature 82
6 ■ File system: Synchronous and asynchronous approaches
to files 114
7 ■ Networking: Node’s true “Hello, World” 136
8 ■ Child processes: Integrating external applications with
Node 174

PART 2 REAL-WORLD RECIPES .................................................... 197


9 ■ The Web: Build leaner and meaner web applications 199
10 ■ Tests: The key to confident code 260

iii
iv BRIEF CONTENTS

11 ■ Debugging: Designing for introspection and resolving


issues 293
12 ■ Node in production: Deploying applications safely 326

PART 3 WRITING MODULES .......................................................359


13 ■ Writing modules: Mastering what Node is all about 361
contents
foreword xiii
preface xv
acknowledgments xvi
about this book xviii
about the cover illustration xx

PART 1 NODE FUNDAMENTALS ...........................................1

1 Getting started 3
1.1 Getting to know Node 4
Why Node? 4 ■
Node’s main features 6
1.2 Building a Node application 8
Creating a new Node project 9 Making a stream class 9

Using a stream 10 Writing a test 12


1.3 Summary 13

2 Globals: Node’s environment 15


2.1 Modules 16
TECHNIQUE 1 Installing and loading modules 16
TECHNIQUE 2 Creating and managing modules 17

v
vi CONTENTS

TECHNIQUE 3 Loading a group of related modules 19


TECHNIQUE 4 Working with paths 21
2.2 Standard I/O and the console object 22
TECHNIQUE 5 Reading and writing to standard I/O 22
TECHNIQUE 6 Logging messages 24
TECHNIQUE 7 Benchmarking a program 25
2.3 Operating system and command-line integration 27
TECHNIQUE 8 Getting platform information 27
TECHNIQUE 9 Passing command-line arguments 28
TECHNIQUE 10 Exiting a program 29
TECHNIQUE 11 Responding to signals 31
2.4 Delaying execution with timers 32
TECHNIQUE 12 Executing functions after a delay with
setTimeout 32
TECHNIQUE 13 Running callbacks periodically with
timers 34
TECHNIQUE 14 Safely managing asynchronous APIs 35
2.5 Summary 38

3 Buffers: Working with bits, bytes, and encodings 39


3.1 Changing data encodings 40
TECHNIQUE 15 Converting buffers into other formats 40
TECHNIQUE 16 Changing string encodings using buffers 41
3.2 Converting binary files to JSON 44
TECHNIQUE 17 Using buffers to convert raw data 44
3.3 Creating your own binary protocol 58
TECHNIQUE 18 Creating your own network protocol 58
3.4 Summary 63

4 Events: Mastering EventEmitter and beyond 64


4.1 Basic usage 65
TECHNIQUE 19 Inheriting from EventEmitter 65
TECHNIQUE 20 Mixing in EventEmitter 68
4.2 Error handling 69
TECHNIQUE 21 Managing errors 69
TECHNIQUE 22 Managing errors with domains 71
4.3 Advanced patterns 73
TECHNIQUE 23 Reflection 73
TECHNIQUE 24 Detecting and exploiting EventEmitter 75
TECHNIQUE 25 Categorizing event names 77
CONTENTS vii

4.4 Third-party modules and extensions 78


TECHNIQUE 26 Alternatives to EventEmitter 78
4.5 Summary 80

5 Streams: Node’s most powerful and misunderstood feature 82


5.1 Introduction to streams 83
Types of streams 83 When to use streams 84 History 85
■ ■

Streams in third-party modules 85 Streams inherit from


EventEmitter 87
5.2 Built-in streams 88
TECHNIQUE 27 Using built-in streams to make a static
web server 88
TECHNIQUE 28 Stream error handling 90
5.3 Third-party modules and streams 91
TECHNIQUE 29 Using streams from third-party modules 91
5.4 Using the stream base classes 94
TECHNIQUE 30 Correctly inheriting from the stream
base classes 94
TECHNIQUE 31 Implementing a readable stream 96
TECHNIQUE 32 Implementing a writable stream 99
TECHNIQUE 33 Transmitting and receiving data with duplex
streams 101
TECHNIQUE 34 Parsing data with transform streams 103
5.5 Advanced patterns and optimization 105
TECHNIQUE 35 Optimizing streams 105
TECHNIQUE 36 Using the old streams API 108
TECHNIQUE 37 Adapting streams based on their
destination 109
TECHNIQUE 38 Testing streams 111
5.6 Summary 113

6 File system: Synchronous and asynchronous approaches


to files 114
6.1 An overview of the fs module 115
POSIX file I/O wrappers 115 Streaming 117 Bulk file I/O
■ ■
117
File watching 118 Synchronous alternatives 118

TECHNIQUE 39 Loading configuration files 119


TECHNIQUE 40 Using file descriptors 120
TECHNIQUE 41 Working with file locking 121
TECHNIQUE 42 Recursive file operations 125
viii CONTENTS

TECHNIQUE 43 Writing a file database 128


TECHNIQUE 44 Watching files and directories 132
6.2 Summary 134

7 Networking: Node’s true “Hello, World” 136


7.1 Networking in Node 137
Networking terminology 137 Node’s networking modules

141
Non-blocking networking and thread pools 142
7.2 TCP clients and servers 143
TECHNIQUE 45 Creating a TCP server and tracking
clients 143
TECHNIQUE 46 Testing TCP servers with clients 145
TECHNIQUE 47 Improve low-latency applications 147
7.3 UDP clients and servers 149
TECHNIQUE 48 Transferring a file with UDP 149
TECHNIQUE 49 UDP client server applications 153
7.4 HTTP clients and servers 156
TECHNIQUE 50 HTTP servers 156
TECHNIQUE 51 Following redirects 158
TECHNIQUE 52 HTTP proxies 162
7.5 Making DNS requests 165
TECHNIQUE 53 Making a DNS request 165
7.6 Encryption 167
TECHNIQUE 54 A TCP server that uses encryption 167
TECHNIQUE 55 Encrypted web servers and clients 170
7.7 Summary 173

8 Child processes: Integrating external applications


with Node 174
8.1 Executing external applications 175
TECHNIQUE 56 Executing external applications 176
Paths and the PATH environment variable 176 Errors when

executing external applications 177


TECHNIQUE 57 Streaming and external applications 178
Stringing external applications together 179
TECHNIQUE 58 Executing commands in a shell 180
Security and shell command execution 181
CONTENTS ix

TECHNIQUE 59 Detaching a child process 182


Handing I/O between the child and parent processes 183 ■
Reference
counting and child processes 184
8.2 Executing Node programs 185
TECHNIQUE 60 Executing Node programs 185
TECHNIQUE 61 Forking Node modules 186
TECHNIQUE 62 Running jobs 188
Job pooling 190 Using the pooler module 191

8.3 Working synchronously 192


TECHNIQUE 63 Synchronous child processes 192
8.4 Summary 194

PART 2 REAL-WORLD RECIPES ........................................197

9 The Web: Build leaner and meaner web applications


9.1 Front-end techniques 200
199

TECHNIQUE 64 Quick servers for static sites 200


TECHNIQUE 65 Using the DOM in Node 204
TECHNIQUE 66 Using Node modules in the browser 207
9.2 Server-side techniques 209
TECHNIQUE 67 Express route separation 209
TECHNIQUE 68 Automatically restarting the server 212
TECHNIQUE 69 Configuring web applications 215
TECHNIQUE 70 Elegant error handling 219
TECHNIQUE 71 RESTful web applications 222
TECHNIQUE 72 Using custom middleware 231
TECHNIQUE 73 Using events to decouple functionality 236
TECHNIQUE 74 Using sessions with WebSockets 238
TECHNIQUE 75 Migrating Express 3 applications
to Express 4 242
9.3 Testing web applications 246
TECHNIQUE 76 Testing authenticated routes 246
TECHNIQUE 77 Creating seams for middleware
injection 248
TECHNIQUE 78 Testing applications that depend on
remote services 250
9.4 Full stack frameworks 256
9.5 Real-time services 257
9.6 Summary 258
x CONTENTS

10 Tests: The key to confident code 260


10.1 Introduction to testing with Node 261
10.2 Writing simple tests with assertions 262
TECHNIQUE 79 Writing tests with built-in modules 263
TECHNIQUE 80 Testing for errors 265
TECHNIQUE 81 Creating custom assertions 268
10.3 Test harnesses 270
TECHNIQUE 82 Organizing tests with a test harness 270
10.4 Test frameworks 273
TECHNIQUE 83 Writing tests with Mocha 273
TECHNIQUE 84 Testing web applications with Mocha 276
TECHNIQUE 85 The Test Anything Protocol 280
10.5 Tools for tests 282
TECHNIQUE 86 Continuous integration 283
TECHNIQUE 87 Database fixtures 285
10.6 Further reading 291
10.7 Summary 292

11 Debugging: Designing for introspection and resolving issues 293


11.1 Designing for introspection 294
Explicit exceptions 294 Implicit exceptions 295
■ ■
The error
event 295 The error argument 296

TECHNIQUE 88 Handling uncaught exceptions 296


TECHNIQUE 89 Linting Node applications 299
11.2 Debugging issues 300
TECHNIQUE 90 Using Node’s built-in debugger 300
TECHNIQUE 91 Using Node Inspector 306
TECHNIQUE 92 Profiling Node applications 308
TECHNIQUE 93 Debugging memory leaks 311
TECHNIQUE 94 Inspecting a running program with
a REPL 316
TECHNIQUE 95 Tracing system calls 322
11.3 Summary 325

12 Node in production: Deploying applications safely 326


12.1 Deployment 327
TECHNIQUE 96 Deploying Node applications to
the cloud 327
TECHNIQUE 97 Using Node with Apache and nginx 332
CONTENTS xi

TECHNIQUE 98 Safely running Node on port 80 335


TECHNIQUE 99 Keeping Node processes running 336
TECHNIQUE 100 Using WebSockets in production 338
12.2 Caching and scaling 342
TECHNIQUE 101 HTTP caching 342
TECHNIQUE 102 Using a Node proxy for routing and
scaling 344
TECHNIQUE 103 Scaling and resiliency with cluster 347
12.3 Maintenance 351
TECHNIQUE 104 Package optimization 351
TECHNIQUE 105 Logging and logging services 353
12.4 Further notes on scaling and resiliency 356
12.5 Summary 357

PART 3 WRITING MODULES ...........................................359

13 Writing modules: Mastering what Node is all about 361


13.1 Brainstorming 363
A faster Fibonacci module 363
TECHNIQUE 106 Planning for our module 363
TECHNIQUE 107 Proving our module idea 366
13.2 Building out the package.json file 370
TECHNIQUE 108 Setting up a package.json file 370
TECHNIQUE 109 Working with dependencies 373
TECHNIQUE 110 Semantic versioning 377
13.3 The end user experience 379
TECHNIQUE 111 Adding executable scripts 379
TECHNIQUE 112 Trying out a module 381
TECHNIQUE 113 Testing across multiple Node versions 383
13.4 Publishing 385
TECHNIQUE 114 Publishing modules 385
TECHNIQUE 115 Keeping modules private 387
13.5 Summary 388

appendix Community 391


index 395
foreword
You have in your hands a book that will take you on an in-depth tour of Node.js. In the
pages to come, Alex Young and Marc Harter will help you grasp Node’s core in a deep
way: from modules to real, networked applications.
Networked applications are, of course, an area where Node.js shines. You, dear
reader, are likely well aware of that; I daresay it is your main reason for purchasing this
tome! For the few of you who actually read the foreword, let me tell you the story of
how it all began.
In the beginning, there was the C10K problem. And the C10K problem raised this
question: if you want to handle 10,000 concurrent network connections on contempo-
rary hardware, how do you go about that?
You see, for the longest time operating systems were terrible at dealing with large
numbers of network connections. The hardware was terrible in many ways, the software
was terrible in other ways, and when it came to the interaction between hardware and
software … linguists had a field day coming up with proper neologisms; plain terrible
doesn’t do it justice. Fortunately, technology is a story of progress; hardware gets better,
software saner. Operating systems improved at managing large numbers of network
connections, as did user software.
We conquered the C10K problem a long time ago, moved the goal posts, and now
we’ve set our sights on the C100K, C500K, and C1M problems. Once we’ve comfortably
crossed those frontiers, I fully expect that the C10M problem will be next.

xiii
xiv FOREWORD

Node.js is part of this story of ever-increasing concurrency, and its future is bright:
we live in an increasingly connected world and that world needs a power tool to con-
nect everything. I believe Node.js is that power tool, and I hope that, after reading this
book, you will feel the same way.
BEN NOORDHUIS
COFOUNDER, STRONGLOOP, INC.
preface
When Node.js arrived in 2009, we knew something was different. JavaScript on the server
wasn’t anything new. In fact, server-side JavaScript has existed almost as long as client-
side JavaScript. With Node, the speed of the JavaScript runtimes, coupled with the event-
based parallelism that many JavaScript programmers were already familiar with, were
indeed compelling. And not just for client-side JavaScript developers, which was our
background—Node attracted developers from the systems level to various server-side
backgrounds, PHP to Ruby to Java. We all found ourselves inside this movement.
At that time, Node was changing a lot, but we stuck with it and learned a whole lot
in the process. From the start, Node focused on making a small, low-level core library
that would provide enough functionality for a large, diverse user space to grow.
Thankfully, this large and diverse user space exists today because of these design deci-
sions early on. Node is a lot more stable now and used in production for numerous
startups as well as established enterprises.
When Manning approached us about writing an intermediate-level book on Node,
we looked at the lessons we had learned as well as common pitfalls and struggles we
saw in the Node community. Although we loved the huge number of truly excellent
third-party modules available to developers, we noticed many developers were getting
less and less education on the core foundations of Node. So we set out to write Node in
Practice to journey into the roots and foundations of Node in a deep and thorough
manner, as well as tackle many issues we personally have faced and have seen others
wrestle with.

xv
acknowledgments
We have many people to thank, without whose help and support this book would not
have been possible.
Thanks to the Manning Early Access Program (MEAP) readers who posted com-
ments and corrections in the Author Online forum.
Thanks to the technical reviewers who provided invaluable feedback on the
manuscript at various stages of its development: Alex Garrett, Brian Falk, Chris
Joakim, Christoph Walcher, Daniel Bretoi, Dominic Pettifer, Dylan Scott, Fernando
Monteiro Kobayashi, Gavin Whyte, Gregor Zurowski, Haytham Samad, JT Marshall,
Kevin Baister, Luis Gutierrez, Michael Piscatello, Philippe Charrière, Rock Lee, Shiju
Varghese, and Todd Williams.
Thanks to the entire Manning team for helping us every step of the way, especially
our development editor Cynthia Kane, our copyeditor Benjamin Berg, our proof-
reader Katie Tennant, and everyone else who worked behind the scenes.
Special thanks to Ben Noordhuis for writing the foreword to our book, and to
Valentin Crettaz and Michael Levin for their careful technical proofread of the book
shortly before it went into production.

Alex Young
I couldn’t have written this book without the encouragement and support of the DailyJS
community. Thanks to everyone who has shared modules and libraries with me over the
last few years: keeping up to date with the Node.js community would have been impos-
sible without you. Thank you also to my colleagues at Papers who have allowed me to

xvi
ACKNOWLEDGMENTS xvii

use my Node.js skills in production. Finally, thanks to Yuka for making me believe I can
do crazy things like start companies and write books.

Marc Harter
I would like thank Ben Noordhuis, Isaac Schlueter, and Timothy Fontaine for all the
IRC talks over Node; you know the underlying systems that support Node in such a
deep way that learning from you makes Node even richer. Also, I want to thank my
coauthor Alex; it seems rare to have such a similar approach to writing a book as I did
with Alex, plus it was fun for a Midwestern US guy to talk shop with an English chap.
Ultimately my heart goes out to my wife, who really made this whole thing possible, if
I’m honest. Hannah, you are loved; thank you.
about this book
Node.js in Practice exists to provide readers a deeper understanding of Node’s core
modules and packaging system. We believe this is foundational to being a productive
and confident Node developer. Unfortunately, this small core is easily missed for the
huge and vibrant third-party ecosystem with modules prebuilt for almost any task. In
this book we go beyond regurgitating the official Node documentation in order to get
practical and thorough. We want the reader to be able to dissect the inner workings of
the third-party modules they include as well as the projects they write.
This book is not an entry-level Node book. For that, we recommend reading Man-
ning’s Node.js In Action. This book is targeted at readers who already have experience
working with Node and are looking to take it up a notch. Intermediate knowledge of
JavaScript is recommended. Familiarity with the Windows, OS X, or Linux command
line is also recommended.
In addition, we’re aware that many Node developers have come from a client-side
JavaScript background. For that reason, we spend some time explaining less-familiar
concepts such as working with binary data, how underlying networking and file sys-
tems work, and interacting with the host operating system—all using Node as a teach-
ing guide.

Chapter roadmap
This book is organized into three parts.
Part 1 covers Node’s core fundamentals, where we focus our attention on what’s
possible using only Node’s core modules (no third-party modules). Chapter 1 recaps

xviii
ABOUT THIS BOOK xix

Node.js’s purpose and function. Then chapters 2 through 8 each cover in depth a dif-
ferent core aspect of Node from buffers to streams, networking to child processes.
Part 2 focuses on real-world development recipes. Chapters 9 through 12 will help
you master four highly applicable skills—testing, web development, debugging, and
running Node in production. In addition to Node core modules, these sections
include the use of various third-party modules.
Part 3 guides you through creating your own Node modules in a straightforward
manner that ties in all kinds of ways to use npm commands for packaging, running,
testing, benchmarking, and sharing modules. It also includes helpful tips on version-
ing projects effectively.
There are 115 techniques in the book, each module covering a specific Node.js
topic or task, and each divided into practical Problem/Solution/Discussion sections.

Code conventions and downloads


All source code in the book is in a fixed-width font like this, which sets it off from
the surrounding text. In many listings, the code is annotated to point out the key con-
cepts, and numbered bullets are sometimes used in the text to provide additional
information about the code.
This book’s coding style is based on the Google JavaScript Style Guide.1 That
means we’ve put var statements on their own lines, used camelCase to format func-
tion and variable names, and we always use semicolons. Our style is a composite of the
various JavaScript styles used in the Node community.
Most of the code shown in the book can be found in various forms in the sample
source code that accompanies it. The sample code can be downloaded free of charge
from the Manning website at www.manning.com/Node.jsinPractice, as well as from
GitHub at the following link: https://github.com/alexyoung/nodeinpractice.

Author Online forum


Purchase of Node.js in Practice includes free access to a private web forum run by Man-
ning Publications where you can make comments about the book, ask technical ques-
tions, and receive help from the authors and from other users. To access the forum
and subscribe to it, point your web browser to www.manning.com/Node.jsinPractice.
This page provides information on how to get on the forum once you’re registered,
what kind of help is available, and the rules of conduct on the forum.
The Author Online forum and the archives of previous discussions will be accessi-
ble from the publisher’s website as long as the book is in print.
You can also contact the authors at the following Google Group URL: https://
groups.google.com/forum/#!forum/nodejsinpractice.

1
https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
about the cover illustration
The caption for the illustration on the cover of Node.js in Practice is “Young Man from
Ayvalik,” a town in Turkey on the Aegean Coast. The illustration is taken from a collec-
tion of costumes of the Ottoman Empire published on January 1, 1802, by William
Miller of Old Bond Street, London. The title page is missing from the collection and
we have been unable to track it down to date. The book’s table of contents identifies
the figures in both English and French, and each illustration bears the names of two
artists who worked on it, both of whom would no doubt be surprised to find their art
gracing the front cover of a computer programming book ... two hundred years later.
The collection was purchased by a Manning editor at an antiquarian flea market in
the “Garage” on West 26th Street in Manhattan. The seller was an American based in
Ankara, Turkey, and the transaction took place just as he was packing up his stand for the
day. The Manning editor didn’t have on his person the substantial amount of cash that
was required for the purchase, and a credit card and check were both politely turned
down. With the seller flying back to Ankara that evening, the situation was getting hope-
less. What was the solution? It turned out to be nothing more than an old-fashioned ver-
bal agreement sealed with a handshake. The seller simply proposed that the money be
transferred to him by wire, and the editor walked out with the bank information on a
piece of paper and the portfolio of images under his arm. Needless to say, we transferred
the funds the next day, and we remain grateful and impressed by this unknown person’s
trust in one of us. It recalls something that might have happened a long time ago.
We at Manning celebrate the inventiveness, the initiative, and, yes, the fun of the
computer business with book covers based on the rich diversity of regional life of two
centuries ago‚ brought back to life by the pictures from this collection.

xx
Part 1

Node fundamentals

N ode has an extremely small standard library intended to provide the


lowest-level API for module developers to build on. Even though it’s relatively
easy to find third-party modules, many tasks can be accomplished without them.
In the chapters to follow, we’ll take a deep dive into a number of core modules
and explore how to put them to practical use.
By strengthening your understanding of these modules, you’ll in turn
become a more well-rounded Node programmer. You’ll also be able to dissect
third-party modules with more confidence and understanding.
Getting started

This chapter covers


■ Why Node?
■ Node’s main features
■ Building a Node application

Node has quickly become established as a viable and indeed efficient web develop-
ment platform. Before Node, not only was JavaScript on the server a novelty, but
non-blocking I/O was something that required special libraries for other scripting
languages. With Node, this has all changed.
The combination of non-blocking I/O and JavaScript is immensely powerful: we
can handle reading and writing files, network sockets, and more, all asynchronously
in the same process, with the natural and expressive features of JavaScript callbacks.
This book is geared toward intermediate Node developers, so this chapter is a
quick refresher. If you want a thorough treatment of Node’s basics, then see our
companion book, Node.js in Action (by Mike Cantelon, Marc Harter, TJ Holoway-
chuk, and Nathan Rajlich; Manning Publications, 2013).
In this chapter we’ll introduce Node, what it is, how it works, and why it’s some-
thing you can’t live without. In chapter 2 you’ll get to try out some techniques by
looking at Node’s globals—the objects and methods available to every Node process.

3
4 CHAPTER 1 Getting started

Preflight check
Node In Practice is a recipe-style book, aimed at intermediate and advanced Node
developers. Although this chapter covers some introductory material, later chapters
advance quickly. For a beginner’s introduction to Node, see our companion book,
Node.js in Action.

1.1 Getting to know Node


Node is a platform for developing network applications. It’s built on V8, Google’s
JavaScript runtime engine. Node isn’t just V8, though. An important part of the Node
platform is its core library. This encompasses everything from TCP servers to asynchro-
nous and synchronous file management. This book will teach you how to use these
modules properly.
But first: why use Node, and when should you use it? Let’s look into that question
by seeing what kinds of scenarios Node excels at.

1.1.1 Why Node?


Let’s say you’re building an advertising server and distributing millions of adverts per
minute. Node’s non-blocking I/O would be an extremely cost-effective solution for
this, because the server could make the best use of available I/O without you needing
to write special low-level code. Also, if you already have a web team that can write
JavaScript, then they should be able to contribute to the Node project. A typical,
heavier web platform wouldn’t have these advantages, which is why companies like
Microsoft are contributing to Node despite having excellent technology stacks like
.NET. Visual Studio users can install Node-specific tools1 that add support for Intelli-
Sense, profiling, and even npm. Microsoft also developed WebMatrix (http://
www.microsoft.com/web/webmatrix/), which directly supports Node and can also be
used to deploy Node projects.
Node embraces non-blocking I/O as a way to improve performance in certain
types of applications. JavaScript’s traditional event-based implementation means it has
a relatively convenient and well-understood syntax that suits asynchronous program-
ming. In a typical programming language, an I/O operation blocks execution until it
completes. Node’s asynchronous file and network APIs mean processing can still occur
while these relatively slow I/O operations finish. Figure 1.1 illustrates how different
tasks can be performed using asynchronous network and file system APIs.
In figure 1.1, a new HTTP request has been received and parsed by Node’s http
module B. The ad server’s application code then makes a database query, using an
asynchronous API—a callback passed to a database read function C. While Node
waits for this to finish, the ad server is able to read a template file from the disk D.

1
See https://nodejstools.codeplex.com/.
Another Random Document on
Scribd Without Any Related Topics
she told all, from the night of the watch to the scene of the trial, and
how she thought Meeah would never leave her. "And many have
asked Abba to give me away" (and she thought of the Rajah's poor
secretary with a smile), "even the great and rich; but I refused, and
Abba did not press me. O mother, I love Meeah! I do love him! Is it
unmaidenly? Is it wrong? Often I have thought it was, and longed to
put on the green dress and take its vows, but Abba always
prevented me. Now do as thou wilt with me."
"It is enough, child," returned the Queen, stroking her soft round
cheek and kissing her forehead. "Enough for thee, and for those who
love thee; and may the Lord bless thee, my darling! I would retire
now, and thou wilt go to Abba and Maria." And Zóra rose and went
to them. Entering her own apartment, she found Maria there; and,
falling on her neck, told her, with many a choking sob, what the
Queen had said. Nor was her suspense continued. The Lady Fatima
had followed her husband, and being announced, at once opened
the subject of her visit. But Zóra could not reply till she had seen her
grandfather; and as Humeed Khan and his nephew had departed,
and Abba had taken his noonday sleep, there was no one to
interrupt them.
I do not think I need follow the scene longer. Under their mutual
explanations, and there was no needless reticence, Zóra confessed
her love, and was blessed by her grandfather, whom she soothed by
the assurance that she would not leave him while he lived. As to the
Lady Fatima, she filled Zóra's mouth with sugar-candy, half
smothered her in flowers, rubbed her hands, feet, and neck with
fragrant paste of sandal-wood; and finally cast over Zóra a rich sheet
of brocaded gold tissue, and hung round her neck a costly necklace,
as she whispered, "From Meeah." No professional women had been
employed, and perhaps they were the only disappointed parties in
Beejapoor; but when the pán leaves and spice were distributed from
house to house to all the mutual friends of both parties, hearty
congratulations followed; and even the female gossips of the city—
who, as elsewhere, were very numerous—were satisfied that it was
a good match.
There are nearly as many ceremonies to complete a Mussulman
betrothal as there are in a marriage; but I do not think my readers,
even my lady readers, would care to follow them through perhaps
two whole chapters, and will rest content in being assured that
Zóra's happiness and state in life have been secured as far as human
foresight could provide, and that there were no more hearty or more
loving wishes for her than those of Sister Maria and her brother
Francis. We, therefore, can leave our old friends the Syud and Zóra,
now familiar with new positions and new hopes, full of contentment
and joyful anticipation to both—more especially to Zóra, whose
mingled feelings of love, gratitude, and faith could perhaps have
been hardly definable.
Among the various letters of congratulation which reached the King
Ibrahim was one from the Viceroy and Captain General of Goa, Dom
Matthias de Albuquerque, which—with a valuable present of various
kinds of arms, European manufactures, and valuables—was brought
by a special ambassador, the Captain Don Miguel de Gama, an
officer of respectability and consideration, well acquainted with the
Persian language, and therefore most fitting for an ambassador. The
ambassador's suite was not numerous; but as he rode into the city
early one morning in a full panoply of bright steel armour, and
presented his credentials at the public durbar in the same
equipment, he created no little excitement. The captain, too, was of
a noble, commanding presence, and had fought well against the
Moors in many battles; and this specimen of the local chivalry of Goa
was in every degree a good representative of its renown.
The letter was in Portuguese, and could have been translated by the
ambassador himself, but the King decided that our friend Francis
d'Almeida should act as secretary and interpreter; and at the early
durbar of the morning, after the ambassador's arrival, the worthy
captain, in no degree abashed by the splendour around him,
marched up the great hall, his armour clanking as he moved, and
saluting King Ibrahim gracefully, laid his packet of letters at the
King's feet.
The captain had come direct to the house of the painter, and had
been comfortably lodged. And how much had Francis and his sister
to hear of their friends at Goa, of the proceedings of Dom Diego,
and of the innumerable changes in the local society; but withal,
there was the certainty that they would have to return to Goa,
whether in his company or apart, to answer the charges which had
been preferred against them by Dom Diego in the inquisition.
And when the Viceroy's letter was read aloud by the priest, after
congratulations upon peace and prosperity of Beejapoor since the
detection and destruction of the conspiracy and insurrection of the
Prince Ismail, a passage followed which related to Francis d'Almeida
and his sister, which may be quoted:—"And furthermore, it hath
been represented to us that a certain priest, Francis d'Almeida, and
his sister Doña Maria, were detected in intrigues with the rebels, and
received from them sundry large sums of money for the supply of
European troops and cannon, which would have been an act beyond
the bounds of goodwill and peace between us, and for which they
have, very justly, been detained by the Government of our friend
and ally, yet, as subjects of the kingdom of Portugal, and as Francis
d'Almeida and his sister belong to religious orders of the Church of
Christ, they should be permitted to answer the charges that have
been made against them; and we, in the name of the King, our
master, request that they may be sent to us in company with our
envoy."
When they returned home, Francis learned from his sister that she
had heard all from the Queen's balcony. She was weeping, but was
not cast down. "I knew it would come upon us sooner or later. The
Church never sleeps, and we cannot delay compliance with this
order;" for a fresh citation had been delivered to them requiring
instant obedience. "We must go, brother, even to the stake, if it be
the Lord's will."
"I fear not, Maria. I have always thought from the first that it would
have been best to go to Goa; and yet the inscrutable ways of
Providence who can follow? Should we have discovered Dom Diego's
letters to Osman Beg or Elias Khan, which on the political charge will
acquit us? As for the rest, conscious as we are of innocence, I fear
nothing. Those, too"—and he pointed to the translations he had
made in company with the Brahmins of the old college in the fort
—"will prove that I have not been lax in my work, though we have
been here. No, sister, let us go. I am to attend the night council, and
the King's reply to the Viceroy will be drafted."
And it was all the good priest could have wished for. The King, the
Queen Dowager, Kureem-oo-deen Chishtee, Ekhlas Khan, the Kazee,
and some others, discussed every point of the Portuguese letter, in
the ambassador's presence (who, divested of his armour, and
dressed in a suit of black Genoa velvet, looked, as he was truly, a
courtly gentleman), and every incident that had occurred at
Beejapoor was detailed. At first the priest of Moodgul had been
under suspicion; but that had passed away owing to the discovery of
the treachery of Dom Diego, and he was left to be dealt with by the
laws of Portugal; but the money he had obtained from Beejapoor
subjects ought to be restored.
The Queen Dowager and the King's wife, as well as Zóra and the
good Lady Fatima, were sincerely grieved by the necessity of the
absence of their friends, and the old Syud, Meeah and his uncle, no
less so. "I shall see thee no more, O friend," said the Syud, grasping
the priest's hand, "Christian and Moslem we have lived together in
amity, and I am thankful. If God will, and thou return hither, we may
meet again; if not, the blessing of Allah be with thee and thine."
And Maria, though her fortitude and her faith supported her in the
trial, yet was sorely pained to leave her friends. Taj-ool-Nissa, who
had become deeply attached to her, and also Zóra, were in despair;
but Maria had her own sources of comfort which never failed her,
and a few days after, with the tears and blessings of all, she and her
brother, well provided with palanquins and tents, and under the
charge of an officer of the Court, who spoke Portuguese, though
after a rude fashion, departed from the Royal city in peace.
CHAPTER VI.
PROCEEDINGS AT GOA.
It was now the beginning of October, and the rains had ceased; all
but those occasional slight showers which lend freshness to the air,
maintain the verdure of the later crops of grain, and furnish those
magnificent sunsets which form the glory of the month. Supplied
with comfortable palanquins, and well provided with horses from the
Royal stables, Maria, her brother, and their friend the envoy, often
rode together in the cool morning air; and Maria enjoyed heartily the
healthful exercise to which, in the crowded city of Beejapoor, she
had long been a stranger.
And thus they sped on from day to day, accompanied by old Pedro
and his wife, who were overjoyed at quitting the great city of the
Moors, and beholding once more their beautiful and beloved Goa.
On the plateau above the Gháts the scenery had been tame and
monotonous; fine undulating plains covered with luxuriant crops of
grain and cotton presented little for admiration or for interest; but
near the crest, heavy forests and broken peaks of mountains
furnished beautiful combinations of wild scenery, and the view over
the broad districts of the Concan was inexpressibly lovely. Away in
the west, the sea stretched to the dim horizon, and here and there
the tiny white speck of a sail could be distinctly seen. Nearer,
however, a dense white mist filled all the valleys and covered the
plain, until the sun, just rising, fell upon it, causing it to glitter like a
sea of molten silver, with occasional rugged peaks rising out of it like
islands. Then all seemed to break up; and while some of the mist
clung to the sides of the greater elevations, the rest gradually rose
into the air and disappeared.
From the last stage the captain envoy left them to give notice of
their arrival. He would fain have taken the King's letter with him, and
the presents by which it was accompanied, which consisted of
vessels inlaid with silver and gold, cloths of gold and silver, four fine
Dekhan horses, and an elephant; but Francis d'Almeida claimed the
privilege of presenting these himself, especially as they were
accompanied by Dom Diego's letters, and he was doubtful as to
what use or misuse might be made of them. He sent, however, by
the captain a letter to the head of the order to which he belonged,
and Doña Maria another to the Lady Abbess of the convent of which
she was a lay sister; and on their arrival in the city, Francis
consigned his sister to the care of the Abbess, who received her with
warm affection, for she had been now several years absent, and she
felt in a short time at rest and at ease among many of her old
friends and associates. In like manner Francis took up his residence
in his old quarters; and it seemed to him that nothing had changed
there, and that all was as peaceful as when he had left it several
years before his sister's arrival.
But within the religious society of Goa there was not peace. There
were strivings between the orders, which the Archbishop strove to
reconcile; and the present Viceroy, Don Matthias de Gama, a kind,
benevolent man in the main, and an excellent and brave soldier,
found it difficult at times to control all and keep up his own
authority. Since Dom Diego's arrival, contention had increased. The
Archbishop had been appealed to by the Superior of the Jesuits, to
demand the surrender of Francis d'Almeida and his sister as
contumacious heretics. Nothing less than their trial and execution
would, he declared, satisfy the demands of the Holy Church, and
preserve discipline in the distant Churches over which only a very
partial supervision could be exercised. Dom Diego preached several
public sermons in the Church of his order, in which the apostasy of
Francis, and his sorceries and evil consorting with heathens and
Moors, were set forth with violent eloquence; and these excited his
hearers to a powerful degree, so that even in the Church they cried
out, "Death to the wretch! Death to the apostate!"
On the other hand, the Archbishop, who well knew Francis
d'Almeida's value as a missionary, his power of language in
addressing the heathen, his knowledge of native dialects, and the
practical use of his translations and ministerial offices, defended him,
and there were many others who followed his example. In process
of these disputes, the Viceroy was appealed to, who declared that
the case was one of ecclesiastical interest only; and though he was
bound to assist the Church, yet the parties accused were beyond his
jurisdiction, residing, or perhaps prisoners, in a powerful kingdom,
with which Portugal was at peace; and, moreover, that in regard to
the allegations against the priest and his sister, the Church itself was
by no means unanimous in opinion. He declined, therefore, to take
any steps in regard to them. If they were contumacious it was no
affair of his. The Church could excommunicate them if it pleased. At
last, however, yielding to pressure, the Viceroy had written, as we
know. The Viceroy had sent a complimentary letter to the King of
Beejapoor, despatched it by a trustworthy soldier, and awaited the
issue with considerable interest as to whether the accused persons
would in reality make submission and appear, or whether, becoming
renegades, as many had done, they would altogether defy the
Church and become Moors. But the arrival of Francis and his sister,
escorted by a Beejapoor officer and a guard of the King's troops,
was proof to all that no contumacy was intended; and he appointed
an early Council, at which the Beejapoor letter should be read, and
necessary consideration made of the whole of the circumstances.
A few days afterwards the Beejapoor envoy and Francis d'Almeida
received their summons from the Viceroy to attend his Council and
the Court, and they went together, the envoy being attended by his
escort, which, in their suits of chain mail and rich apparel, made an
imposing appearance in the thronged streets of the city; and on their
arrival at the palace were ushered at once into the presence of the
Viceroy, who, with his staff about him, was seated on the viceregal
throne.
An artillery salute was fired in honour of the envoy, who was
graciously received; and after some general and kind inquiries after
the health of King Ibrahim, to which he replied in indifferent
Portuguese, the rest of the conversation was carried on through
Francis d'Almeida, who acted as interpreter. Then the Viceroy,
receiving the King's letter, said, "As this contains matter for political
consideration, we will adjourn, Sir Envoy, to our Council Hall, where
it shall be read before all my councillors of State and dignitaries of
the Church, who are our advisers." Then, rising and taking the
envoy's hand, he led him into the adjoining apartment, which was
the Council Chamber.
It was a fine room, though to the envoy's idea somewhat bare of
decoration. A large Turkey carpet was laid upon the floor, and in the
centre was a long table covered with red cloth, with inkstands and
writing paper ready for use. The Viceroy seated himself at the head
of the table, placed the envoy in a chair on his right hand, and the
dignitaries of the Church, military and naval commanders, all
wearing their rich uniforms and decorations, took their seats with
the civil officers, according to precedence and custom. The whole
formed a dignified and, indeed, august assembly, well befitting the
powerful kingdom it represented.
Then the letter of King Ibrahim was read, and the Viceroy remarked
that it was written in excellent Portuguese, and asked his envoy to
Beejapoor who wrote it, and the captain said—
"In my presence was it written by the priest Francis d'Almeida. The
King himself dictated the letter in Persian, in my presence, and the
purport was fully known to me; and the priest and I compared the
Portuguese version with the Persian, and they corresponded exactly.
Moreover, your Excellency will observe that the original Persian is
written below, and signed by the King himself. There can be no
doubt of the authenticity of both."
"But," continued the Viceroy, "in the latter portion of this document
grave charges are made against Dom Diego di Fonseca, an eminent
servant of the Church, who is now the accuser of Francis d'Almeida
and his sister Maria, and at whose instance, and that of the Holy
Father of the Inquisition, their presence was required in order to
answer the charges brought against them, and we ought not to
enter into this subject without his presence. As it is a political affair
entirely, involving the risk of disagreement between our Government
and that of our friend King Ibrahim the Second, we, the
representatives of Portugal, have full authority to investigate it,
leaving the alleged offenders against the Church to be dealt with by
the Holy Inquisition. Let, therefore, Dom Diego be summoned
instantly; and till he arrives we call upon Francis d'Almeida to give an
account of his apparent flight from Moodgul, and his evasion of the
summons of the Inquisition."
"I was not a free agent, may it please your Excellency and the
members of this Council," said Francis d'Almeida. "I was preparing to
leave Moodgul after the citation was publicly read by my colleague
when I was arrested, by order of the Queen Regent of Beejapoor,
and forwarded by Dilawar Khan, the Governor of Moodgul, to the
fort of Juldroog, where we were confined for more than a month on
charges of having conspired against the State in assisting the
conspiracy of the Prince Ismail and Eyn-ool-Moolk, and obtaining
large sums of money for the purpose of engaging European soldiers
and cannon. Finally, we were sent to Beejapoor, where we remained
under surveillance until the King should return, as the Queen Regent
did not consider she had authority to try so momentous a question
herself. Then suddenly, and as by special Providence, certain papers
fell into the hands of the Queen's Government, by which it appeared
that my colleague, and not I, had been in correspondence with the
rebels, partly independently, and partly by means of Osman Beg, the
Killadar or Governor of the fort of Juldroog, who was arrested, tried
on the evidence of papers found in his possession, convicted of
treason, and sentenced to death."
"And he was beheaded, Francis d'Almeida?" asked the Viceroy.
"Not so, my lord; his life was spared on the intercession of his
cousin, Abbas Khan; but he was banished from the kingdom, and
has taken his departure for Mecca with his father."
Francis d'Almeida's address had continued for some time, for he
described minutely and concisely all that had occurred, with the
particulars of which we are fully acquainted.
"And where are the papers you allude to?" asked the Superior of the
Inquisition tartly. "Who can vouch for their authenticity if they are
produced?"
"My lord," returned the Beejapoor envoy, "we are not careless in
regard to papers of importance at Beejapoor. At the first discovery of
them, after the death of Yacoot, the Abyssinian, I, as knowing
somewhat of your language, was asked to read those in Portuguese;
but I could not, and the Padré Sahib was directed by the Queen to
do so, and to translate them into Persian; then her seal was affixed
to each one of them, and she added her private signature, and all
the Ministers signed and sealed them. Then the packet was sealed
until opened by order of the King, and sealed again with his seal,
which all men know, and which is appended to his letter."
"You were all very careful," said the chief Inquisitor, with a sneer,
"but where are these letters?"
At this moment Dom Diego was ushered in. He wore the religious
dress of his order, but he at once threw back his cowl, and his eyes
and those of Francis d'Almeida met once more. In the one was a
scowl of bitter hate, and the brows were almost knit together; but
those of Francis wore their usual mild expression, and betrayed no
emotion; nay, their look of innocence seemed to make a favourable
impression upon all present.
After bending his knee to the Archbishop and the Grand Inquisitor,
Dom Diego drew his fine figure to its full height, looked round the
room towards all, and then said to the Viceroy, "For what purpose
am I required here, most illustrious Sir? I have not been apprised
that matters which are under the cognisance of the Holy Inquisition
could be transferred to a Council like this; and I request that my
protest may be entered against any interference with what has been
already arranged."
"There is no intention, Dom Diego, on our part to interfere with the
proceedings of the Holy Office. This is a political question, which
thou wilt know of when thou hast heard the letter of the King of
Beejapoor. Let it be read to him," he continued, "as also the minutes
of Francis d'Almeida's statement."
Dom Diego heard all without reply; but it was easy to see that his
mind was far from tranquil. A nervous tremor appeared to be
irrepressible; his mouth twitched as if by convulsion, and he twisted
his hands together in continuous action, which could be seen even
under his robe.
"And now, my lords," said the Viceroy, rising, "the most important
part of our sitting is to commence; and I have to beg, in the name
of justice, that your utmost vigilance may be employed to clear up
what has been alleged. The papers alluded to in the letter are in
possession of the envoy from Beejapoor. Let him produce them."
"They are here, my lord," returned the envoy, producing two small
bundles tied up in waxed cloth, which was sealed with the King's
seal. "First, I ask you to bear me witness that these seals are intact;
and particularly you, O most illustrious Sir, into whose hands I
commit the packets."
The Viceroy examined the papers carefully, and said, "I see no
reason to doubt what has been said. The seals are undisturbed; but
judge for yourselves, noble sirs." And when the packets had passed
round, the Viceroy demanded to know whether they were to be
accepted, and a general reply was given that they were.
"These are the letters which were found on the body of Yacoot, the
Abyssinian. Let them be first examined," said the Beejapoor envoy;
"and my lords will please to remark that all have the Queen's seal,
as those first found were examined by her; and that there are forty-
two documents which, with the exception of those required by the
Council, should be returned to me, and a receipt given to me for the
remainder. And now, noble sirs, have I your permission to open the
first packet?"
"I again protest," cried Dom Diego, rising suddenly, "against any
examination of those papers here. Let them be given over to the
custody of the Holy Office, which will examine and authenticate
them, and produce such as it considers necessary for the elucidation
of the truth."
But the pretence was too shallow to escape the detection of many of
the experienced men who heard the protest, and the majority at
once declared that they should be opened, and publicly read and
registered.
Then the Viceroy took the first packet and handed it to his own
interpreter, a fine-looking Mussulman gentleman, who had just
entered the room, and who spoke not only Arabic and Persian
fluently, but Portuguese, for he had lived for some years in Portugal,
acting as interpreter of documents sent by the Indian Government.
Abdoolla-bin-Ali was a man held by everyone in the highest esteem
and honour, and his presence carried assurance with it to all the
Council, and very especially to the Beejapoor envoy and Francis
d'Almeida, whose personal explanations would be needed no longer.
"On the cover is written," said the Moonshee, "'This packet contains
forty-two documents, eighteen in Portuguese and twenty-four in
Persian, and bears the King's seal.'" Then he broke the seal carefully
and unwound the silken cord with which the parcel was fastened.
There appeared within several other coverings, two separate
packets, one of which was labelled in Persian, "Eighteen Portuguese
papers and letters," and bore the Queen's seal, which was shown to
all.
"I think, my lords," said the Viceroy, "that to prevent doubt I had
better read these aloud to the Council, and they can examine each
separately afterwards, if they please;" and, this being assented to,
he took up the first, which was addressed to the most illustrious the
Vizier Eyn-ool-Moolk, Bahadoor, and dated from Moodgul. As the
letter was opened, everyone could see the strong bold characters of
the handwriting of Dom Diego, which were known to all or most
present, and a general murmur ran through the Council, as if of
wonder and astonishment; but no one spoke, and, in breathless
silence, the Viceroy read on.
It was a long letter, and we may be pardoned for not following it in
detail; but the writer acknowledged the receipt of Eyn-ool-Moolk's
"letter offering the Padré Dom Diego de Fonseca a command in the
new Royal army. That if he joined it with a force of one thousand
Europeans, his pay would be at the rate of one lakh of rupees per
month, and the same for every thousand more brought to the Royal
standard." It then proceeded to state, that considering the expense
of European troops in the field, the pay would be insufficient; and
that, in case of the force capturing Beejapoor, there was no mention
of prize shares in the treasure and jewels that would become the
property of the army. It would be necessary also to confer upon the
writer the district of Bunkapoor, with all its forts and dependencies.
That as the cowardly and imbecile Government of Goa would never
be induced to take part in the war, or to send any of its soldiers, the
writer must be provided with funds to go to Portugal to raise as
many men as possible, with whom he pledged himself to return at
the expiration of a year, and disembark them at any port on the
coast that might be chosen.
In conclusion, the writer professed his high admiration for and
sympathy with, the movement to substitute the virtuous Prince
Ismail for the tyrant who now ruled over Beejapoor, and ended by
praying that the measure might receive the blessing and guidance of
the Almighty; and at the end was written,
"By mine own hand,
"D. Diego di Fonseca."
"Are there more like that?" asked the Grand Inquisitor of Dom Diego,
in a whisper; "if so, thou art lost!"
"Let them read what they will," he answered. "I will satisfy my lord
presently."
More! yes, there was much more. Every one of the letters contained
sketches of arrangements to be made, estimates of cost, professions
of good faith and sincerity. Several of them contained receipts for
large sums of money, partly in gold, partly in bills; and by his own
admissions Dom Diego had received upwards of three lakhs of
rupees in cash, while assurances of payment as far as ten lakhs,
beside a fourth share of the plunder of Beejapoor, was promised and
accepted.
Then followed letters to Elias Khan, as the lieutenant-in-chief of Eyn-
ool-Moolk, which were in a more familiar strain; which spoke of
revelries they had enjoyed together; of the pleasures they would
share when they met again; complained that he could not absent
himself without suspicion, but that he was about to rid himself of his
coadjutor, whose sister Maria he would bring with him, a lovely girl
of his own country, who would put to shame all the dusky beauties
of his friend's harem; and wine from Portugal of the choicest kind,
which should enliven them. In another, the gold sent by the
company under Pedro di Diaz, that is, twenty thousand "hoons," had
arrived safely; with many other details, all written in the same bold
hand, and signed with the same very remarkable signature. As they
were read, minutes were made of them by the secretary. Every
paper was compared as to the seals of the Queen Regent and the
Beejapoor Ministers, and that every precaution had been used to
prevent any chance of their being tampered with, was a fact which
was not without significance in the assembly.
And the Persian letters to Elias Khan from Eyn-ool-Moolk, with one
from the Prince Ismail, bestowing an honorary title as commander of
five thousand in the Royal army, with an estate of twenty villages in
the district of Bunkapoor—all confirmed the tenor of the Portuguese
letters of Dom Diego; while, with the transmission of money through
Elias Khan, assurance was given that as soon as the Europeans
appeared in the field, the whole of the Talooq of Bunkapoor would
be made over to him as stipulated. There were others from Osman
Beg to Elias Khan, descriptive of private revels at Moodgul, in a
house in the town hard by the Padré, where wine of the choicest
was stored up, and was plentiful, and the most beautiful dancing
women of the country round were assembled. And he wrote of the
Padré as being a jovial fellow, who winked at everything, and who
had shown him at the chapel, privately, the beautiful Doña Maria,
whom he was to bring away with him when he came with his troops.
"She is more lovely than anything on the earth's face, and no Houri
of Paradise could be more beautiful;" and much more to the same
effect, written in the loose, not to say indecent, style prevailing
among those like Osman Beg at Beejapoor. Then the letters seemed
suddenly to come to an abrupt close. After May of that year none
had passed between the parties; and, indeed, by this time, the
whole conspiracy had collapsed in the defeat and deaths of the
principal conspirators. There only remained the exposure of the guilt
of all by the discovery of the letter on the person of the Abyssinian.
The second packet contained, for the most part, letters from Eyn-
ool-Moolk to Elias Khan; but they gave particulars of the agreement
with the illustrious and learned Padré D. Diego di Fonseca; of the
moneys transmitted to be paid to him; and in one, the Padré's
receipt, in Persian and Portuguese, of the twenty thousand hoons,
and for other sums, amounting to about two lakhs of rupees.
"Hast thou nothing to reply, brother?" said the Inquisitor, in an
earnest whisper to Dom Diego. "Thou art condemned by thine own
hand; would it had been cut off and burnt before those letters were
written."
Diego did not reply. He rose, and those who were watching him saw
that his lips were white, and his dark complexion had assumed an
ashy hue, and that he spoke as if he were choked by thirst. Yet he
drew himself up bravely, and said with an assumed air of unconcern
and bravado, "I am not on my trial, most illustrious Señor, else my
reply would be sharp and certain. In these letters, which purport to
be mine, I only see the cunning toils with which Francis d'Almeida
strove to entangle me, and failed; and when they had nothing to fall
back upon they fled. Their being arrested is a mere mockery. As to
the handwriting of the letters," and he took up one before the
Inquisitor, "they are all like this, forgeries. The fair Maria is an
accomplished scribe, and can copy any style of writing, even that of
heathen characters; and I do not at all marvel at her excellent
imitation of mine. But, my lords, as I said, I am not on my trial; and
no opinion can be given on the subject either till I am, or till that
shameless priest and his sister are pronounced guilty of heresy and
conspiracy by the Holy Inquisition, and perish for their heresies at
the stake."
"Let that be as the good God wills," said the Viceroy, calmly.
"Meanwhile, these papers are so strong against thee, that we, in
virtue of our authority, declare thee to be a prisoner, and arrest thee
in the name of our gracious King. Thou shalt have honourable
treatment as a gentleman, and thou shalt be lodged in this palace,
till the time when the trial of Francis d'Almeida and his sister comes
on. When may it be, Holy Father?"
"It is fixed for Friday," answered the Inquisitor, calmly; "that the
guilty may be ready for the auto-da-fé on the Sabbath. But your
Excellency, pardon me, errs in keeping a son of the Church in arrest
till then, and I will gladly be security for his appearance when
needed."
"Impossible," replied Don Matthias de Gama. "Nevertheless I will
take the votes of the Council." And he did so; but none supported
the Grand Inquisitor's proposal except one, another priest, and Dom
Diego was consigned to the care of the men-at-arms, who
conducted him to an upper chamber luxuriously furnished, and told
him that his servants would be sent when they could be found to
attend to his comfort.
What were the thoughts of this man as he heard the door of his
large airy apartment locked after him and bolted outside. All his
reliance on the comparative insignificance of Francis d'Almeida had
given place to a fearful sense of his power with those terrible
documents in his own handwriting to appeal to. Forgeries! who
would believe that, with all the evidence of his handwriting in the
Holy Office, and the Archbishop's records to appeal to for
comparison? His accusation against Francis and his sister had
depended for success upon his words only, which he believed would
overwhelm those of the modest, unassuming priest; and in the
death of him and of his sister would be future safety. But the
revelation of his own conduct, of the moneys he had obtained, of his
treasonable plots, denounced by the King Ibrahim, had rendered his
malignity abortive. And now the grim trial, the horrible torture, the
death by fire, like that he had witnessed of hapless victims writhing
in agony at the stake——
Escape! was it possible? He went to one of the windows and looked
through the jalousies, for he could not open one of them.
Impossible! his room was over fifty feet from the ground, and the
wall was smooth, without a projection; and he turned away with a
shudder.
Presently his servant came. "Have you seen Pedro di Diaz?" he
asked.
"I have, Señor," was the reply; "and he is now waiting for me at the
quay. He wants to know whether he is to stand out to sea or
remain."
"Tell him," replied Dom Diego, "that he is to leave the ship's boat
with six of the best of the men in it, and to take the brigantine to
the mouth of the harbour, without exciting suspicion. I will be with
him on Friday night; but if I do not come by Sunday, I shall be
dead."
CHAPTER VII.
THE INQUISITION.
The appointed day arrived. The sudden arrest of Dom Diego, his
confinement to the Viceregal palace, and the refusal of the Grand
Inquisitor's security for him, had created a sensation in Goa which
had only one chance of solution—the trial by the Inquisition. On the
other hand, the well-known character of Francis d'Almeida, and the
devotion of his lovely sister, gave to the case an interest such as had
been rarely felt, and never exceeded, in the city. All had many
personal friends, Dom Diego especially among the Jesuits, to whose
order he belonged; Francis d'Almeida among those of his own order,
the Dominicans, and among the ordinary clergy of the province,
headed by the noble Archbishop; and in his sweet sister every lady
in Goa was interested. Could so holy and learned a woman be
actually tried on charges of sorcery and conspiracy with Moors and
heathens? And yet it was to be; and many thought that the
interference by the Viceroy with the acts of the Holy Office was at
once presumptuous and wicked. From early morning the principal
street of the city and the square of the Inquisition had been
thronged with eager inquirers, and the most conflicting rumours
were prevalent; some, that Dom Diego had confessed his guilt, and
would be made over to the Inquisition, to be formally condemned;
others, that Francis d'Almeida and his sister had made similar
confessions, and that all parties had been originally bound in one
confederation, but had split upon the division of money of which
they had become possessed. In short, the wildest rumours prevailed,
particularly as to the sorceries of d'Almeida and his sister, which they
had learned from heathen priests and exercised upon their coadjutor
to drive him away from the place he had usurped. All these opinions,
however, were set at rest by the appearance of two processions:
one, that of soldiers of the Viceroy having Dom Diego in their
charge; the other of monks and holy nuns, who escorted Francis
d'Almeida and his beautiful sister. Among the soldiers Dom Diego
marched firmly and proudly, his tall, martial figure being conspicuous
from his general bearing, and the haughty manner with which he
regarded the crowds who gazed upon him; the others, from the
apparent simplicity of the brother and sister, who walked hand in
hand, with a calm and submissive demeanour which deeply affected
many. No one dared to speak, but whispered comments passed
among the crowd; and women, and men too, wept that such
servants of God might be condemned ere the day passed, not only
to torture, but to the horrible death by fire in the auto-da-fé of the
next Sabbath, which promised to be one of unusual interest.
So, passing on, both parties entered the portal of the great gloomy
building, Dom Diego being the first. And when a short colloquy had
passed between the officers of the Viceroy's guard and those of the
Inquisition as to the delivery of the prisoner, he was taken on by the
familiars. Before the monks and sisters, with the two others, had
entered the gate, they had recommenced a hymn which had been
sung at intervals during their progress, the sweetness and solemnity
of which had had a profound effect; and it again arose steadily and
sweetly, with a rich and fervent melody which penetrated every
heart, as knees were bent and hats doffed reverently as the
processions passed, while the simple words caused many a silent
prayer to arise to the Throne of Grace.
When in trouble and in fear,
To thee we cry, O Mother dear!
Behold our sorrows, bitter weeping,
Yet in all trial humbly keeping
Trust in thee, Maria!

Mother of Jesus, lowly born,


On earth by human sorrow torn;
Yet in thy glory resting now,
Heedful of all thy creatures' woe,
Hear our prayer, Maria!

Those who have daily died the death


Of those who suffer slander's breath;
Those who in dread judgment's hour
Their simple hearts to thee outpour,
Pity them, O Maria!

Support them in their hour of need,


To cheer them with thy comfort speed,
Lest without thee they go astray,
Mother, with thee all bright their way,
Having no fear, Maria!
While the chant proceeded, the procession entered the door, and its
sweet melody was heard faintly as it passed up the broad corridor
which led to the great hall of the Inquisition.
It was a bare, whitewashed room, with narrow windows near the
ceiling, which let in the cool air and a small degree of light; but
when the eye, dazzled by the glare without, had become
accustomed to the dimness within, everything—nay, even the
emotions in every face—were distinctly visible. There was a separate
place for the accuser; another for the prisoners; and a third for any
witnesses that might have to be called. In the centre was a long
narrow table covered with coarse black serge, with inkstands, pens,
and paper at intervals; and the Inquisitors sat in tall, straight-
backed, wooden chairs around, the Grand Inquisitor's position being
in the centre of the right hand side, in a raised chair, so that he
could overlook all. There were no guards near Dom Diego now; and
his cowl being thrown back, his grim, swarthy features and bold
flashing eyes were distinctly visible. The prisoners were directed to
stand in their allotted space; and the venerable Archbishop, in his
robes, with a number of clergy, sat on one side, but took no part in
the inquiry.
After the proceedings had been opened by a prayer and a solemn
chant, the Grand Inquisitor rose from his seat, and said—
"Holy fathers, we have heard with unfeigned sorrow, grief, and
amazement the scandal to the Church which has arisen under the
unseemly contentions in the Mission Church at Moodgul, where, in
the midst of Moors and Pagans, the Lord Christ hath graciously
hitherto supported our poor measures for making known His gospel
to those otherwise benighted and damnable peoples. In process of
years many hundreds have been gathered to the foot of the Cross,
and hundreds have died in a steady belief in the sacraments of the
Holy Church, while many live in the exercise of a devout Christian
faith and good works. Within the last few months, however, grievous
troubles have arisen, as is known to our Father in God the illustrious
Archbishop; and on the direct accusations of Dom Diego di Fonseca,
the local vicar, we summoned Francis d'Almeida and his sister Maria
to answer his charges. This citation was publicly made known to
them both by being read in the Mission Church; but, instead of
obeying it, both departed from Moodgul under the escort of Moorish
soldiers, and went or were conveyed to Beejapoor, where they
resided until a demand from His Excellency the Viceroy was made
for them, and they were sent hither.
"Thus, holy fathers, ye have to determine in what manner the priest
Francis d'Almeida is guilty, as also his sister, of the formal charges
which I now read. Then you will hear the justification of the
prisoners; and you will, with prayer to the Almighty, pronounce
judgment upon them. Diego di Fonseca, in the name of the Holy
Trinity, I call upon you to swear that what you are about to say is
true;" and on the formal oath being administered to him, he stood
erect, and with all the energy and musical tone of his fine voice, he
spoke to the following effect.
I think, however, that I do right in refusing an attempt to detail all.
In the outset of his oration, he referred to his services in China, in
the Spice Islands, in Bengal, among the savage tribes of Malays and
Moors; of perils by land and sea, and of the many human souls he
had rescued from everlasting destruction.
"I was a humble follower of St. Francis Xavier," he continued, "and
strove to follow his example. Then, worn out and weary, I came to
Goa, and would have returned to Portugal for a season, but new
work at Moodgul was opened to me, and in my zeal I accepted it.
"Holy fathers, when I arrived there I found a mockery of a Church.
My coadjutor, more a heathen than a Christian, had suffered the
most ordinary offices of the Church to be utterly neglected. He was
incessantly employed in the study of Pagan languages, mythology,
and Scripture, and of Moorish languages, and infidel books. To the
people he invariably preached in a tongue they call Canarese. He
read the services of the Church in the same tongue, and he
desecrated the holy service by using it even in the mass. Instead of
our own language, his sister taught it in the schools, and thus
perverted the minds of children, who might have been made wise
unto salvation.
"It was all horrible! horrible! this perpetual study of books, which
contain besides damnable theological dissertations; works on
sorcery, divination, astrology, and all the evil sciences denounced by
the Church, for which so many have suffered; and I warned him on
many occasions, for I was willing to save them both, to abandon
these evil courses and damnable heresies. And at first Francis
d'Almeida strove to justify himself by declaring that he read Hindoo
books to understand best how to controvert their doctrine; and
declared that he was even translating the holy gospels and services
of the Church into the language of the people, that they might
understand what they profess to believe. Was any heresy ever so
complete? Ye, O reverend fathers, know how the Scriptures are
forbidden to be read except under ghostly direction and counsel, and
how corruption and unbelief must needs arise under such
proceedings as those of Francis d'Almeida towards his ignorant flock.
I found remonstrance of no use; he avoided me with disrespect; and
in the congregation a party was growing up against him which it was
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!

ebookname.com

You might also like