100% found this document useful (6 votes)
205 views55 pages

Complete Node Js 8 The Right Way Practical Server Side JavaScript That Scales 1st Edition Jim Wilson PDF For All Chapters

Server

Uploaded by

sapethperde
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 (6 votes)
205 views55 pages

Complete Node Js 8 The Right Way Practical Server Side JavaScript That Scales 1st Edition Jim Wilson PDF For All Chapters

Server

Uploaded by

sapethperde
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

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

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/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

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/
textboxfull.com

Full Stack JavaScript Learn Backbone js Node js and


MongoDB Mardan Azat

https://textbookfull.com/product/full-stack-javascript-learn-backbone-
js-node-js-and-mongodb-mardan-azat/

textboxfull.com

Node js Design Patterns Master best practices to build


modular and scalable server side web applications 2nd
Edition Casciaro
https://textbookfull.com/product/node-js-design-patterns-master-best-
practices-to-build-modular-and-scalable-server-side-web-
applications-2nd-edition-casciaro/
textboxfull.com

Learning Node Moving to the Server Side Early Release


Shelley Powers

https://textbookfull.com/product/learning-node-moving-to-the-server-
side-early-release-shelley-powers/

textboxfull.com
Professional Node js Building Javascript Based Scalable
Software 1st Edition Teixeira Pedro

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

textboxfull.com

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/
textboxfull.com

Fullstack Node js The Complete Guide to Building


Production Apps with Node js Davit Guttman

https://textbookfull.com/product/fullstack-node-js-the-complete-guide-
to-building-production-apps-with-node-js-davit-guttman/

textboxfull.com

Jump Start Node js Get Up to Speed With Node js in a


Weekend 1st Edition Nguyen Don

https://textbookfull.com/product/jump-start-node-js-get-up-to-speed-
with-node-js-in-a-weekend-1st-edition-nguyen-don/

textboxfull.com

Instant Node js Starter 1st Edition Teixeira Pedro

https://textbookfull.com/product/instant-node-js-starter-1st-edition-
teixeira-pedro/

textboxfull.com
Node.js 8 the Right Way
Practical, Server-Side JavaScript That
Scales
by Jim R. Wilson

Version: P1.0 (January 2018)


Copyright © 2018 The Pragmatic Programmers, LLC. This book is licensed to the
individual who purchased it. We don't copy-protect it because that would limit your
ability to use it for your own purposes. Please don't break this trust—you can use this
across all of your devices but please do not share this copy with other members of your
team, with friends, or via file sharing services. Thanks.

Many of the designations used by manufacturers and sellers to distinguish their


products are claimed as trademarks. Where those designations appear in this book, and
The Pragmatic Programmers, LLC was aware of a trademark claim, the designations
have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit,
The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the
linking g device are trademarks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher
assumes no responsibility for errors or omissions, or for damages that may result from
the use of information (including program listings) contained herein.

About the Pragmatic Bookshelf


The Pragmatic Bookshelf is an agile publishing company. We’re here because we want
to improve the lives of developers. We do this by creating timely, practical titles, written
by programmers for programmers.

Our Pragmatic courses, workshops, and other products can help you and your team
create better software and have more fun. For more information, as well as the latest
Pragmatic titles, please visit us at http://pragprog.com.

Our ebooks do not contain any Digital Restrictions Management, and have always been
DRM-free. We pioneered the beta book concept, where you can purchase and read a
book while it’s still being written, and provide feedback to the author to help make a
better book for everyone. Free resources for all purchasers include source code
downloads (if applicable), errata and discussion forums, all available on the book's
home page at pragprog.com. We’re here to make your life easier.

New Book Announcements


Want to keep up on our latest titles and announcements, and occasional special offers?
Just create an account on pragprog.com (an email address and a password is all it
takes) and select the checkbox to receive newsletters. You can also follow us on twitter
as @pragprog.

About Ebook Formats


If you buy directly from pragprog.com, you get ebooks in all available formats for one
price. You can synch your ebooks amongst all your devices (including iPhone/iPad,
Android, laptops, etc.) via Dropbox. You get free updates for the life of the edition. And,
of course, you can always come back and re-download your books when needed.
Ebooks bought from the Amazon Kindle store are subject to Amazon's polices.
Limitations in Amazon's file format may cause ebooks to display differently on different
devices. For more information, please see our FAQ at pragprog.com/frequently-asked-
questions/ebooks. To learn more about this book and access the free resources, go to
https://pragprog.com/book/jwnode2, the book's homepage.

Thanks for your continued support,


Andy Hunt
The Pragmatic Programmers
The team that produced this book includes: Andy Hunt (Publisher),
Janet Furlow (VP of Operations), Brian MacDonald (Managing Editor),
Jacquelyn Carter (Supervising Editor), Candace Cunningham (Copy Editor),
Potomac Indexing, LLC (Indexing), Gilson Graphics (Layout)

For customer support, please contact [email protected].

For international rights, please contact [email protected].


Table of Contents

Acknowledgments

Preface
Why Node.js the Right Way?
What’s in This Book
What This Book Is Not
Code Examples and Conventions
Online Resources

Part I. Getting Up to Speed on


Node.js 8

1. Getting Started
Thinking Beyond the web
Node.js’s Niche
How Node.js Applications Work
Aspects of Node.js Development
Installing Node.js

2. Wrangling the File System


Programming for the Node.js Event Loop
Spawning a Child Process
Capturing Data from an EventEmitter
Reading and Writing Files Asynchronously
The Two Phases of a Node.js Program
Wrapping Up

3. Networking with Sockets


Listening for Socket Connections
Implementing a Messaging Protocol
Creating Socket Client Connections
Testing Network Application Functionality
Extending Core Classes in Custom Modules
Developing Unit Tests with Mocha
Wrapping Up

4. Connecting Robust Microservices


Installing ØMQ
Publishing and Subscribing to Messages
Responding to Requests
Routing and Dealing Messages
Clustering Node.js Processes
Pushing and Pulling Messages
Wrapping Up
Part II. Working with Data

5. Transforming Data and Testing


Continuously
Procuring External Data
Behavior-Driven Development with Mocha and Chai
Extracting Data from XML with Cheerio
Processing Data Files Sequentially
Debugging Tests with Chrome DevTools
Wrapping Up

6. Commanding Databases
Introducing Elasticsearch
Creating a Command-Line Program in Node.js
with Commander
Using request to Fetch JSON over HTTP
Shaping JSON with jq
Inserting Elasticsearch Documents in Bulk
Implementing an Elasticsearch Query Command
Wrapping Up

Part III. Creating an Application


from the Ground Up
7. Developing RESTful Web Services
Advantages of Express
Serving APIs with Express
Writing Modular Express Services
Keeping Services Running with nodemon
Adding Search APIs
Simplifying Code Flows with Promises
Manipulating Documents RESTfully
Emulating Synchronous Style with async and await
Providing an Async Handler Function to Express
Wrapping Up

8. Creating a Beautiful User Experience


Getting Started with webpack
Generating Your First webpack Bundle
Sprucing Up Your UI with Bootstrap
Bringing in Bootstrap JavaScript and jQuery
Transpiling with TypeScript
Templating HTML with Handlebars
Implementing hashChange Navigation
Listing Objects in a View
Saving Data with a Form
Wrapping Up

9. Fortifying Your Application


Setting Up the Initial Project
Managing User Sessions in Express
Adding Authentication UI Elements
Setting Up Passport
Authenticating with Facebook, Twitter, and Google
Composing an Express Router
Bringing in the Book Bundle UI
Serving in Production
Wrapping Up

10. BONUS: Developing Flows with Node-RED


Setting Up Node-RED
Securing Node-RED
Developing a Node-RED Flow
Creating HTTP APIs with Node-RED
Handling Errors in Node-RED Flows
Wrapping Up

A1. Setting Up Angular

A2. Setting Up React

Copyright © 2018, The Pragmatic Bookshelf.


Early praise for Node.js 8 the
Right Way
Node.js 8 the Right Way is an excellent guide for building robust
Node.js applications and making use of the extensive Node.js
ecosystem. Using realistic applications from several different
domains, it gives a highly useful and thorough description of the
process of building, testing, and deploying real-world Node.js
programs.

→ Dan Scales
Principal Engineer, Google Inc.
Without the original Node.js the Right Way, I wouldn’t be where I
am today. This book leapfrogged me from being a casual Node.js
developer to loving the event loop and knowing how to build
effective distributed systems in Node.js. It led me to writing clean,
idiomatic, and highly understandable JavaScript—both in Node.js
and in the browser. This update will do the same for readers.

→ Kyle Kelley
Senior Software Engineer, Netflix
Jim’s update to his engaging, wide-ranging deep dive into how to
solve actual problems using Node.js taught even this old dog some
new tricks. Hats off to Jim for clearly demonstrating how to get the
most out of Node.js.

→ Mark Trostler
Software Engineer, Google Inc.
Jim Wilson shows the correct way, the way that will definitely make
you a better Node.js developer, giving you many techniques,
insights, and—most of all—some really cool stuff. Node.js 8 the Right
Way provides loads of good practices and reveals some of the lower-
level interactions of Node with the system. In a Node.js shop, this
book is a must for seniors’ reference and a must for new hires.

→ Peter Perlepes
Software Engineer, Growth
Acknowledgments
I’m so grateful to have had the opportunity to write this book. And
I’m especially thankful for my editor, Jackie Carter—your thoughtful
feedback made this book what it is today.

Thank you, dear reader, and readers of the Beta releases. Your
errata reports made the book better than it would have otherwise
been.

I’d also sincerely like to thank the whole team at The Pragmatic
Bookshelf. Thanks for your kind patience, and all of your hard work
to polish this book and find all of my mistakes.

I’d like to thank all of my reviewers. Your keen observations have


helped make this book even more technically correct (the best kind
of correct). In no particular order:

Dan Scales Mark Ethan Gary


Trostler Chamberlain
Rick Waldron Nick Capito Peter Hampton

Luca Peter Perlepes Dominic Schulz


Mezzalira
Maricris S. Nonato
And I want to thank my amazing family, too. Dear Ruthy, you are my
inspiration; never stop fighting! Emma and Jimmy, even though
you’re both growing up too fast, I can’t wait to see all the great
things you’ll do.

For anyone I missed, I hope you’ll accept my apologies. Any


omissions were certainly not intentional, and I have nothing but
gratitude for you in my heart.

Copyright © 2018, The Pragmatic Bookshelf.


Preface
In recent years, two big shifts have happened in the practice of
writing software—and Node.js has been at the forefront of both.

First, software is becoming increasingly asynchronous. Whether


you’re waiting on a Big Data job, interacting with end users, steering
a quadcopter, or simply responding to an API call, chances are you’ll
need asynchronous programming techniques.

Second, JavaScript has quietly become the world’s standard code-


execution environment. It’s everywhere: in web browsers, modern
NoSQL databases, DIY robots, and now on the server as well.

Node.js is an integral part of these trends, and it has taken off in a


big way.
Why Node.js the Right Way?
Way back in March of 2010, I gave a lightning talk titled “Full-Stack
JavaScript” at the NoSQL Boston conference. Back then, and even
more so now, I knew that using JavaScript for every layer of the
application stack was not only possible, but was a great way to
reduce software complexity.

When each layer of your stack speaks JavaScript, you sidestep


impedance mismatches and facilitate code reuse. Node.js is an
important piece of the puzzle, filling the middle space between your
front-end user-facing code and your data-storage layer.

The Right Way in this book’s title refers to both the process of
learning Node.js and the practice of writing Node.js code.

Learning Node.js
As with any growing technology, there are plenty of resources
available for learning Node.js. Unfortunately, many of those
resources are narrowly focused on serving up web resources.

The web is great, but it’s not enough, and it’s not the whole story of
Node.js. Node.js is about more than just serving web apps, and this
book treats it that way.

Node.js 8 the Right Way teaches you the concepts you’ll need to be
an effective Node.js programmer, no matter what kinds of programs
you need to write.

Writing Node.js
One thing I love about JavaScript is that there are seven ways to do
anything. There’s breathing room, where developers can explore and
experiment and find better approaches to everything.

The community of Node.js developers, the conventions in Node.js


development, and even the semantics of the JavaScript language
itself are all rapidly evolving. With eyes to the near future, the code
examples and recommendations in this book reflect current best
practices and standards.
What’s in This Book
This book is for intermediate to advanced developers who want to
learn how to write asynchronous JavaScript for the server using
Node.js. Some prior JavaScript experience will definitely help, but
you don’t have to be an expert.

The book proceeds in three parts, outlined here briefly.

Part I: Getting Up To Speed on Node.js 8


Part I is about getting you up to speed on Node.js 8. You’ll write
Node.js programs that use core modules—and a few external
modules as well—to do things like interact with the filesystem, spin
up a cluster of worker processes, and manage network connections.

Getting Started
Chapter 1, ​Getting Started​, introduces the Node.js event loop,
explaining how it empowers Node.js to be highly parallel and single-
threaded at the same time. This chapter also outlines the five
aspects of Node.js development that frame each subsequent chapter
and has some brief instructions on getting Node.js installed on your
machine.

Wrangling the File System


In Chapter 2, ​Wrangling the File System​, you’ll start writing Node.js
programs. If you’ve done any server-side programming in the past,
chances are you’ve had to access a filesystem along the way. We’ll
start in this familiar domain, using Node.js’s filesystem tools to
create asynchronous, nonblocking file utilities. You’ll use Node.js’s
ubiquitous EventEmitter and Stream classes to pipe data, and you’ll
spawn and interact with child processes.
Networking with Sockets
We’ll expand on those concepts while exploring Node.js’s network
I/O capabilities in Chapter 3, ​Networking with Sockets​. You’ll create
TCP servers and client programs to access them. You’ll also develop
a simple JSON-based protocol and a custom class for working with
these messages. To develop unit tests for the code, you’ll use
Mocha, a popular Node.js test harness.

Connecting Robust Microservices


Then, in Chapter 4, ​Connecting Robust Microservices​, we’ll branch
away from the Node.js core and into the realm of third-party
libraries. You’ll use npm to import ØMQ (pronounced “Zero-M-Q”)—a
high-efficiency, low-latency library for developing networked
applications. With ØMQ, you’ll develop programs that communicate
using several important patterns, such as publish/subscribe and
request/reply. You’ll create suites of programs that work together in
concert, and you’ll learn the clustering tools to manage them.

Part II: Working with Data


In Part II, you’ll work with real data and lay the groundwork for an
end-to-end application. This starts with processing data files in a
testable way. You’ll also learn to compose rich command-line utilities
using Node.js and interact with HTTP services.

Transforming Data and Testing Continuously


Chapter 5, ​Transforming Data and Testing Continuously​, kicks off an
ongoing project that spans Part II and Part III. You’ll download the
catalog from Project Gutenberg, an online resource for ebooks in the
public domain. Using a module called Cheerio, you’ll write Node.js
code to parse the data files and extract the important fields. You’ll
use npm, Mocha, and an assertion library called Chai to set up
continuous testing, and you’ll learn to use Chrome DevTools for
interactive debugging.

Commanding Databases
In Chapter 6, ​Commanding Databases​, you’ll insert the extracted
Project Gutenberg catalog into an Elasticsearch index. To get this
done, you’ll write a command-line utility program called esclu using a
Node.js module called Commander. Since Elasticsearch is a RESTful,
JSON-based datastore, you’ll use the Request module to interact
with it. You’ll also learn to use a handy and powerful command-line
tool called jq for manipulating JSON.

Part III: Implementing an Application


Part III is where everything comes together. You’ll develop web
services that mediate between your API users and your back-end
data services. End users don’t interact directly with APIs, though, so
for that you’ll implement a beautiful UI. At the end, you’ll tie it all
together with session management and authentication.

Developing RESTful Web Services


Node.js has fantastic support for writing HTTP servers, and in
Chapter 7, ​Developing RESTful Web Services​, you’ll do exactly that.
You’ll use Express, a popular Node.js web framework for routing
requests. We’ll dive deeper into REST semantics, and you’ll use
Promises and async functions for managing code flows. In addition,
you’ll learn to configure your services using the nconf module, and
keep them running with nodemon.

Creating a Beautiful User Experience


With the web services in place, in Chapter 8, ​Creating a Beautiful
User Experience​, you’ll craft a front end for them. You’ll learn how to
assemble a front-end project using a Node.js-based build tool called
webpack, along with a host of peer-dependency plugins for it. You’ll
transpile your code for consumption by the browser using
TypeScript, a language and transpiler from Microsoft that features
inferred type checking. To make your UI look modern and fabulous,
you’ll bring in Twitter’s Bootstrap styling framework, and implement
templating with Handlebars.

Fortifying Your Application


Chapter 9, ​Fortifying Your Application​, is where everything comes
together. You’ll combine the user experience with the web services
from the previous two chapters for an end-to-end solution. Using
Express middleware, you’ll create authenticated APIs and implement
stateful sessions. You’ll also learn how to use npm’s shrinkwrap option
to insulate yourself from upstream module changes.

Developing Flows with Node-RED


After Part III concludes, there’s a special bonus chapter on Node-
RED. Chapter 10, ​BONUS: Developing Flows with Node-RED​, walks
you through this clever visual editor for designing event-based code
flows. It ships directly with Raspbian, the default operating system
of Raspberry Pi.

Using Node-RED, you can quickly stub out exploratory HTTP APIs. I’ll
show you how!

Appendices on Angular and React


In case you’re interested in using the front-end frameworks Angular
and React, Appendix 1, ​Setting Up Angular​, and Appendix 2, ​Setting
Up React​, show you how to integrate them with webpack and
Express. The appendixes will help you put the pieces in place to start
experimenting, but they don’t take the place of a good tutorial on
how to fully develop with them.
What This Book Is Not
Before you commit to reading this book, you should know what it
doesn’t cover.

Everything About Everything


At the time of this writing, npm houses more than 528,000 modules,
with a growth rate of more than 500 new modules per day.[1] Since
the ecosystem and community around Node.js is so large and still
growing so rapidly, this book does not attempt to cover everything.
Instead, this short book teaches you the essentials you need to get
out there and start coding.

In addition to the wealth of Node.js modules available, there’s the


added complexity of working with non-Node.js services and
platforms. Your Node.js code will invariably act as an intermediary
between various systems and users both up and down the stack. To
tell a cohesive story, we’ll naturally only be able to dive deep on a
few of these, but always with an eye to the bigger picture.

MEAN
If you’re looking for an opinionated book that focuses only on a
particular stack like MEAN (Mongo, Express, Angular, and Node.js),
this is not it! Rather than prescribe a particular stack, I’ll teach you
the skills to put together the Node.js code, no matter which back
end you connect to or front end you choose to put on top.

Instead of MongoDB, I’ve selected Elasticsearch to back the projects


in this book because it’s increasingly popular among experienced
Node.js developers, as evidenced by a 2016 survey by RisingStack.[2]
Moreover, with its REST/JSON API, Elasticsearch offers a way to ease
into HTTP services as a consumer before jumping into writing your
own.

This book also shies away from front-end JavaScript frameworks.


The two most popular front-end frameworks at the time of this
writing are React, by Facebook,[3] and Angular, by Google.[4] This
book covers neither of them in detail, by design. They both deserve
more coverage than fits in these pages.

I want you to be the best Node.js coder you can be, whether you
use any particular database or front-end framework.

JavaScript Beginner’s Guide


The JavaScript language is probably the most misunderstood
language today. Although this book does discuss language syntax
from time to time (especially where it’s brand-new), this is not a
beginner’s guide to JavaScript. As a quick quiz, you should be able to
easily read and understand this code:

​ c
​onst​list = [];
​ ​
for​(​let​i = 1; i <= 100; i++) {
​ ​f​(!(i % 15)) {
i
​ list.push(​'FizzBuzz'​);
​ } ​else​​if​(!(i % 5)) {
​ list.push(​'Buzz'​);
​ } ​else​​if​(!(i % 3)) {
​ list.push(​'Fizz'​);
​ } ​else​{
​ list.push(i);
​ }
​ }

You may recognize this as a solution to the classic programming


puzzle called FizzBuzz, made famous by Jeff Atwood in 2007.[5]
Here’s another solution—one that makes gratuitous (and
unnecessary) use of some of the newer JavaScript features.

​ '
​use strict'​
;
​ ​
const​list = [...Array(100).keys()]
​ .map(n => n + 1)
​ .map(n => n % 15 ? n : ​'FizzBuzz'​
)
​ .map(n => isNaN(n) || n % 5 ? n : ​'Buzz'​
)
​ .map(n => isNaN(n) || n % 3 ? n : ​'Fizz'​
);

If you don’t recognize the techniques used in this code, that’s


expected! You’ll learn to use several of them, and many others, in
this book.

A Note to Windows Users


The examples in this book assume you’re using a Unix-like operating
system. We’ll make use of standard input and output streams, and
pipe data between processes. The shell session examples have been
tested with Bash, but other shells may work as well.

If you run Windows, I recommend setting up Cygwin.[6] This will give


you the best shot at running the example code successfully, or you
could run a Linux virtual machine.
Code Examples and Conventions
The code examples in this book contain JavaScript, shell sessions,
and a few HTML/XML excerpts. For the most part, code listings are
provided in full—ready to be run at your leisure.

Samples and snippets are syntax-highlighted according to the rules


of the language. Shell commands are prefixed by $.

When you write Node.js code, you should always handle errors and
exceptions, even if you just rethrow them. You’ll learn how to do this
throughout the book. However, some of the code examples lack
error handling. This is to aid readability and save space, and
sometimes to provide opportunities for reader tasks at the end of
the chapter. In your code, you should always handle your errors.
Online Resources
The Pragmatic Bookshelf’s page for this book is a great resource.[7]
You’ll find downloads for all the source code presented in this book,
and feedback tools, including a community forum and an errata-
submission form.

Thanks for choosing this book to show you Node.js the right way.

Jim R. Wilson
December 2017

Footnotes

[1] http://www.modulecounts.com/

[2] https://blog.risingstack.com/node-js-developer-survey-results-2016/

[3] https://facebook.github.io/react/

[4] https://angularjs.org/

[5] https://blog.codinghorror.com/why-cant-programmers-program/

[6] http://cygwin.com/

[7] http://pragprog.com/book/jwnode2/node-js-8-the-right-way

Copyright © 2018, The Pragmatic Bookshelf.


Part 1
Getting Up to Speed on
Node.js 8
Node.js is a powerful platform for developing server-
side JavaScript.

In this first part, you’ll write Node.js code, beginning


with the familiar domain of the command line and then
expanding into the realm of microservices. Along the
way, you’ll learn to structure your code into modules,
use third-party modules from npm, and take
advantage of the latest ECMAScript language features.
Chapter 1

Getting Started
An old programming adage says that while functionality is an asset,
code is a liability.[8]

Throughout this book, as you learn to harness Node.js, keep in mind


that the best line of code is the one you never had to write. If you
can get something for free, take it!

However, the nature of a technical book is to teach you how to do


something, even if somebody has already done it for you. By
understanding how things work, you’ll be better able to build on top
of them.

So we’ll be progressing in stages. In the beginning, you’ll be working


at the lowest levels of Node.js—getting to know the environment,
the language, and the fundamental APIs. As you master those, you’ll
learn how to use other peoples’ modules, libraries, and services to
replace some of that code and go to the next level.

By the end, you’ll see where it’s possible to make great gains using
existing libraries, and where it makes sense to implement the
functionality yourself. At the end of the day, this wisdom is the
power that will distinguish you from a novice developer.
Thinking Beyond the web
A lot of the buzz around Node.js is focused on the web. In truth,
Node.js serves a bigger purpose that people often miss. Let’s use a
map to see where Node.js fits in the broader scheme of things.

Imagine the set of all possible programs as the inhabitants of a vast


sea. Programs that have similar purposes are near each other, and
programs that differ are further apart. With that picture in mind, take
a look at this map. It shows a close-up of one particular outcrop in
this sea, the Island of I/O-Bound Programs.

I/O-bound programs are constrained by data access. These are


programs where adding more processing power or RAM often makes
little difference.

East of the mountain range, we find the client-side programs. These


include GUI tools of all stripes, consumer applications, mobile apps,
and web apps. Client-side programs interact directly with human
beings, often by waiting patiently for their input.
Exploring the Variety of Random
Documents with Different Content
his head. The Arch-priest's office is naturally more sacerdotal in its
nature than that of his comrades, for it is he who is entrusted with the
due performance of all the services of the temple, and he too assists
at the solemn ceremony of censing the crystal altar of the Sun, as I
have already shown. He is also the custodian of the awful Fountain
of Rejuvenation, though his guardianship is shared by other
members of the inner ring. One day, finding the venerable head of
the council in an unusually expansive mood, I ventured to question
him openly upon the properties of this sacred well, this Zem-Zem of
Meleagrian un-faith. He replied that its medicated waters, though
highly beneficial to a mortal born of the Earth, would prove fatal to
any Meleagrian rash enough to attempt their use. Moreover, he
added that should anyone plunge alone and unattended into this
well, the terrific suction of the current beneath would infallibly drag
the body under, never to reappear. I then questioned him if many
such accidents had ever occurred, whereupon he answered dryly
that none had happened in his own experience; which equivocal
reply I interpreted as admitting that fatal incidents in the past were by
no means unknown. I then twitted him jokingly for not renewing his
own youth, of course with all proper precautions, in the fountain of
his charge, to which he replied with considerable asperity and horror,
using the most solemn Meleagrian form of denial: "May the God
perish first and the Sun be darkened!" After this vigorous negation
he took his departure with some abruptness, nor could I ever entice
him to speak again of the fountain.
I fully realise that my account of the hierarchy or governing class of
Meleager is both incomplete and unsatisfactory, but I must plead
again the many difficulties of obtaining information which I have
already mentioned. In fact, it is from two sources only that I can
derive any details whatever, these being my own limited
opportunities of observation and discovery and the rare statements
that the Arch-priest lets fall from time to time, for I am not on
confidential terms with any other member of the council. From Hiridia
and my friends of the nobility I can gather absolutely nothing, for the
simple reason that their own ignorance of the private affairs of their
ruling caste is even greater than mine. Indeed, the marvel is that I
have been able to compile even the small amount I have inscribed
here, considering the obstacles in my way of acquiring knowledge. I
must sum up therefore by stating that I have very little
communication with that body of councillors with whom my own
position and prerogative are so closely interwoven, this state of
affairs being due wholly to the persistent refusal of the latter to take
me into their confidence.
IX
Of the nobility I can speak with more confidence, for with many of
them I am on terms of intimacy and friendship. The well-bred
gentleman is not confined in our own world to any special climate or
nation, for he is to be found equally under a white, a yellow, a brown
and even a black skin; and the gentle type is also indigenous on the
planet of Meleager.
The aristocracy of Meleager is closely connected with the land, and it
is to some extent strongly impregnated with feudal principles. Every
noble is either the owner of an estate, be it large, moderate or small,
or else is connected by family ties with the actual landowner. Each
house forms a distinctive gens in itself, and all its male members are
entitled to bear a badge, which is its peculiar mark. These badges at
first suggested to my mind a relic of totem-kin, but I soon changed
my opinion on this point, and now hold the family badge to be
heraldic in its aim and use. I gather that the adoption of a
conspicuous badge or emblem for each family is of considerable
antiquity, and perhaps derives from reports made by the Meleagrian
envoys on Earth at the period of the Crusades, when coat-armour
came into fashion among the chivalry of Western Christendom.
The mass of the nobles exhibits various degrees of wealth and
influence, and I have noted the existence of some ill-feeling between
the leading magnates and the smaller landowners. The social
cleavage between the two sets is however imperceptible, and the
constant intermarriage between the families of what I may call the
major and the minor barons tends to eradicate many cases of
jealousy. This landed aristocracy has, of course, its chief residence
in the country districts, though the wealthier families possess houses
in the cities in addition. The country house of Meleager is usually of
moderate size, and consists of a low square white-washed mansion
enclosing a courtyard. The native love of colonnades is prominently
exhibited in these houses, which are frequently surrounded on all
sides by loggias that can be utilised according to the varying
conditions of weather. The arrangements within are somewhat
primitive according to our own luxurious standards of the twentieth
century, but they are not without a sufficiency of comfort. The floors
are generally tiled; there are no rugs or carpets, save some skins of
beasts; the furniture, though often elaborately carved, is not plentiful.
There are no family portraits, for the art of painting pictures is
unknown, but in compensation for this defect there is always the
curious family chapel or mausoleum. This has usually a low domed
roof pierced by windows of coloured glass that admit only a dim light
within the chamber which seems very similar to the columbaria of the
Romans, from whom I conclude this idea has been borrowed by their
unknown admirers. Rows of small semicircular apertures line the
walls, many of these standing empty, whilst not a few are occupied
by busts of deceased members of the family. Beneath these effigies
are placed small urns of metal or marble which contain the ashes, for
cremation has for sanitary reasons been made compulsory in
Meleager for many centuries past. Some of these busts are of no
small artistic merit, and evidently well portray the features of the
noble ancestors; others again are of inferior workmanship; whilst
some are obviously merely conventional in their treatment. Such a
collection certainly forms rather a gruesome substitute for a family
portrait gallery, but its atmosphere does not seem to depress the
spirits of the present generation, for I am always cheerfully invited to
enter and inspect these queer oratories. The surrounding gardens
are often beautiful, but are far less artificial than our own. One broad
long flagged terrace usually suffices for the family to stroll; otherwise
the paths and lawns are unkempt and neglected. These pleasances
are however full of a luxuriant growth of wild or half-wild flowers, so
that I found myself often being reminded of the exuberant gardens of
old-world Italian villas in past days, before the late irruption of
wealthy cosmopolitan tourists had succeeded in thoroughly
vulgarising Italy and modernising all its old peaceful haunts.
Country life as pursued in Meleager varies little in its essence from
that of our Earth, mutatis mutandis, for time is pretty evenly divided
between the attractions of sport and the claims of estate
management and domestic concerns. Everything is, of course,
conducted in a manner that would appear as primitive to our
pampered sportsmen as it would seem suggestive to the antiquary,
for both field sports and agriculture have remained here in the
mediæval, or even sometimes in the archaic, stage of development.
Firearms, though not unknown, are at least never employed, so that
in hunting the spear, the net, the trap and even the bow still
constitute the chief weapons of the chase. All ploughing is performed
by oxen with wooden implements, and the thorough cultivation of the
crops is on a tiny scale. Again and again have the conditions of
Meleagrian rural life recalled to me the old-world bucolic practices of
Tuscany and Castile, that even down to the close of the nineteenth
century retained so many picturesque features of remote classical
times. The tenor of existence in the country is quiet enough, and
would prove unspeakably dull and irksome to the majority of our
modern squires; but it must be remembered that the Meleagrian
landowners have no newspapers, no novels, no Stock Exchange, no
party politics to sweeten and distract their daily round, so that they
are perfectly content to follow in the secure footsteps of their
forefathers. Should the younger men find the calm routine of country
life wearisome, there are other avenues of occupation open to such
restless souls. In the first place there is the army, which is officered
solely by members of the aristocracy, some of whom make a
permanent profession of their military duties and attain in due course
to the higher commands therein. The usual plan is, however, for the
younger sons of the noble houses to spend some three or four years
in the army, after which they marry and come to settle in homes of
their own, where they busy themselves for the rest of their lives with
a medley of sport, agriculture and domestic economy. Again, the life
at Court is open to a certain number of those who care neither for a
career in the army nor for the monotony of the countryside. Here
they participate in the constant variety of the palace, and hope to win
honorary appointments in the royal household. A few, more
adventurous still than their fellows, proceed to Barbaria either for the
purpose of better hunting, or for the sake of the harder and more
exciting life in a new sphere of energy. Some proportion of these
latter obtain grants of land in this less than half-occupied territory,
where they found new estates modelled on the old lines, much as
the younger scions of our gentle English houses emigrated and
settled in Virginia. Such experiments moreover are strongly
commended and encouraged by the special councillors who are
charged with the conduct of colonial affairs.
Yet another and a far more important means of escape from the
alleged tedium of family or rustic routine is the career of the
probationer, who aspires eventually to be elected a member of the
hierarchy. This ambition cannot, however, be gratified before the age
of thirty, when the intending candidate is admitted to the school of
the neophytes. Here for a year he receives a course of lectures on
Meleagrian history and is taught the rudiments of Latin grammar, but
no instruction in reading or writing is yet afforded him. At the end of a
twelvemonth of such preliminary training, the neophyte is either
rejected as unfit or unsuitable, or else he is admitted a probationer of
the seminary attached to the Temple of the Sun. In that case he
receives a five years' course of far more advanced tuition; he is
taught to read, write and speak the Latin language; and presumably
he is also instructed in astronomy, politics, theology and other
subjects concerning which his existing notions must be strangely
vague or wholly erroneous. This long period of instruction entails a
severe strain on the pupil, who is henceforth cut off from all private
and external ties and interests, for he is never allowed to quit the
precincts of his seminary. Of his final election and reception into the
council of the hierarchy I have spoken elsewhere. Whether or no any
candidate has ever failed to obtain his election and has been
consequently compelled to remain in the institution for years,
perhaps for the term of his lifetime, I cannot say; yet I do know for a
fact that for its inmates there is but one door leading out of the
seminary of probationers and that is the door which admits to the
council chamber.
I always enjoy my occasional visits to the country seats of the
nobility, where the calm useful healthy life affords an agreeable
change to me from the atmosphere of the palace, which seems
always charged with mystery and intrigue. The genuine greeting of
my host and the members of his family, the delightful blend of divine
honours and of frank hospitality wherewith I am everywhere
received, the pride shown in their farms and agricultural schemes,
the general air of repose and safety, all tend to soothe a mind that
has grown perplexed and wearied with the endless cares of an
exalted but anomalous office. The conversation of these uneducated
but well-bred persons is certainly not exciting, and might fairly be
described as trivial, but really I do not think, from past experience,
that it is more trifling or banal than the average talk of the British
aristocracy which of recent years has elevated sport and money-
making to be the prevalent topics of society (using that term in its
narrow technical application). And though all these excellent folk in
Meleager are of necessity quite illiterate in the sense that they
cannot read and write, their memory is marvellous, so that often after
the evening meal the different members of the household recite
whole poems in the Meleagrian language, or else tell stories that are
by no means devoid of wit and imagination. Often too there is
singing to the native lute of sweet melodious songs, which are well
rendered by the fresh voices of the young performers.
The land tenure of Meleager may perhaps be best described as a
modified form of primogeniture. The family estate, whether large or
small, descends in tail male, and only in the failure of masculine
issue in the whole family to the female heirs of the last possessor.
This strict entail is, however, subject to certain limitations, which tend
to allow provision for the widow and daughters of the landowner.
Moreover, all members of the family have a species of life interest in
the estate, so long as they continue unmarried. Thus on the death of
a father, the eldest-born will inherit, but the new owner's younger
brothers (and also his unmarried uncles), if still residing under the
family roof, own the right to remain in their old home. Patriarchal life
in this manner becomes highly developed, and the family council
consisting of all its male and all its unmarried female members can
exercise considerable power over all private affairs within the scope
of the family circle. Thus the expulsion of an unworthy relative can
be arranged, and this inherent family rule is admitted and upheld by
the hierarchy. A noble thus expelled forfeits his right to bear the
family badge, and also has to relinquish the crimson cloak and tunic
of his order. A member so degraded sinks automatically into the
ranks of the plebeian or third estate, and is generally lost sight of.
Such incidents are rare, but they do occur occasionally, and this
private form of prerogative to drive into social exile is undisputed.
Although a very distinct line is drawn between the Reds and the
Greens, between the noble and the mercantile classes, there seems
no contempt or envy of class on either side. Such jealousy as exists
is rather noticeable within the ranks of the aristocracy itself, wherein,
though nominally all are of equal rank, some are rich and some poor,
some influential and some of little account. And the same remark
holds good of the conditions prevailing in the mercantile class.
Taxation of the landed interest is raised in two ways: first by a direct
tax on land itself, which is apportioned at certain intervals; and
second, by a poll-tax on every noble. Occasionally a landed estate
left without any male heirs is sold for the benefit of the female
inheritors; but it is clear that in the vast majority of cases the present
estates in Meleager have descended in unbroken succession and
unreduced in area for many generations.
As to the characteristics of the Meleagrian nobles, doubtless they
have their failings, but these in my estimation are fully redeemed by
their many good qualities. There is apparent some display of
haughtiness in the higher nobility towards other less wealthy
members of their own caste, but their attitude and bearing towards
their many dependents and also towards the general populace would
be worthy of imitation even in our so-called democratic world. Of
course such intimacy as I can attain with them is necessarily limited,
when one considers my own range of knowledge and their utter
inability to grasp the meaning of any one of the many serious
questions that perpetually vex my mind. I sometimes have the
sensation of living in a world of shadows, with which I sport and even
converse, for the mental gulf fixed between me and them is
fathomless and unbridgeable. Even my Hiridia, faithful friend and
delightful companion though he be, seems often a plaything rather
than a co-equal being of the same flesh and blood as myself. I can
study all these people and analyse with ease their simple empty
minds; I can sympathise with their artless pleasures and pastimes; I
can play and sing and hunt and bathe and feast with them;—but I
cannot talk with them seriously any more than can a septuagenarian
professor carry on a rational conversation with a child. Yet all the
same they are charming grown-up children; and was it not the Divine
Master of our world who more than once insisted that to share His
promised kingdom all His grown-up hearers must become as little
children? Nevertheless, despite such consoling thoughts, the fact
remains that I am always lonely.

Of the mercantile class I intend to say very little. So much that I have
just written applies with equal force to the Greens, or second estate
of the realm. I am often entertained by the leading merchants of
Tamarida and Zapyro, but these occasions really produce little more
than the exchange of polite formalities, and I know far less of these
persons than I do of the nobility. A portion of this class is connected
with the land in the form of yeomen, or small freeholders, whose
properties are however confined to Barbaria or to the poorer districts
of the Regio Solis. In their case the law of primogeniture is enforced
more strictly than amongst the landed aristocracy, for as the
yeoman's estate is reckoned insufficient to provide for all the males
of the family, only the eldest son enjoys the paternal acres. The
younger sons are accordingly dispatched to make their living or
fortune in some trade, and it is usually the stalwart young men of this
small landed stock who supply the greater part of the petty officers in
the army. The great majority of the Greens, as they are commonly
termed, are traders either on a large or a small scale, though a
certain number fill some of the lesser official posts of stewards and
assistants in connection with the work of the hierarchy. In the case of
members of this order who have amassed considerable wealth and
are desirous of entering the class of the nobles, application is made
to the council, and such appeals are either granted or refused after a
full hearing of the circumstances. The royal consent is likewise
necessary for the bestowal of this coveted privilege; and I may add
that such applications constitute the sole exception to the general
rule, that the nobles are never given to intrigue with myself. Naturally
they are jealous concerning the prerogative of their order, and some
at least are certain to resent fiercely any such attempts of outsiders
to be admitted to their ranks. A good many of such appeals are
rejected, but in the event of a successful application a large
contribution has to be paid to the coffers of the temple and the
palace; a landed estate has somehow to be purchased, usually in
Barbaria, and then the fortunate postulant doffs the green robes and
dons the red, which he is now permitted to wear, and also assumes
the use of a badge granted him by the King, who selects the emblem
he deems most suitable. The position of the new-comers for a
considerable time, perhaps for a couple of generations, is not an
enviable one, for they are treated coldly and looked at askance by
the majority of their fellow-nobles. But as the older folk pass away,
and memories grow shorter, the new lord, or rather his progeny,
becomes gradually absorbed by matrimonial connection into the
mass of the nobility, and intermingles with the rest. Still, the stigma of
having risen from the Greens clings, I fancy, to this type of pseudo-
aristocratic house for a long time. On the other hand, marriage with a
junior member of the nobility at once confers the husband's rank on
a bride of the second estate, who henceforth ceases to hold open
intercourse with her own family. Contrariwise, ladies of the nobility
who ally themselves with merchants or yeomen sink to the level of
their husbands' station.

With the populace again I have more intimacy and sympathy than
with the Greens, and through my attendants and bodyguard at the
palace I am brought more closely into touch with the people at large.
This third estate of the realm consists of all the manual labourers,
the artisans, the fisher-folk, and in short all such persons as live by
receiving wages, whether in money or kind. I have already hinted
that their condition and well-being form the constant care of the
councillors, who see that their homes are sanitary, well built and
generally adequate, whilst the wages paid must be deemed sufficient
to support the individual or his family in decency and comfort. In fact,
the supervision of this, the largest and economically the most
important section of the community, constitutes the first care of the
hierarchy. The people seem hale and happy, nor do they exhibit any
envy of the better-fed and better-clad Greens, nor yet of the majestic
and privileged Reds. The rules of family life prevail less strongly here
owing to the wider dispersal of its members, but they are nominally
identical with those in the classes above. There are no law courts in
Meleager, and usually disputes and difficulties in this class are
settled, as I have already shown, in the judgment hall of the capital,
where I sit on most days. The women-folk of the third estate live in
less seclusion than do those of the nobility and merchants, a result
that is due (as in our Mohammedan countries) to the necessity of the
poor having to perform their marketing and daily business in public.
This same class also may be said to include the numerous tribe of
indentured labourers, mostly from Barbaria, whose status somewhat
resembles that of the Roman slaves under the Empire. Vice and
drunkenness, though by no means unfrequent, are not conspicuous
in this class; whilst the police patrols keep a pretty sharp eye on the
landlords of the lower sort of wine-shop and brothel. These resorts of
the more dissipated of the people are also visited at times by the
councillors charged with their management and reputation, so that
the streets of Tamarida at night would compare favourably with those
of most European cities, and such debauchery as does exist is
assuredly kept well concealed behind doors and is not allowed to
offend the eyes or the ears of the passer-by in the streets, which,
though dark and narrow, can be safely traversed by all after nightfall.
A few cases of quarrelling and use of the knife occur and are
severely punished by the lash whenever the culprits are brought to
book; deliberate murder is very rare; theft is not frequent; assaults on
women and children are practically unknown. So far as my
observations tend, I can sum up without hesitation by saying that the
proletariat of Meleager is a remarkably happy, healthy, well-behaved,
industrious and sober body under what I may call the benign
despotism of councillors who have not only been educated to
command by years of special training, but also possess a natural gift
for such functions.
X
I should not like the reader from anything I have written hitherto to
carry away the impression that, because I am myself debarred from
their society, the women of Meleager own a status at all similar to
that prevailing in Mohammedan countries. On the contrary, setting
aside the exceptional case of their semi-divine monarch, the sex has
little to lament on the score of inferior or unfair treatment. The
Council of Seventy, it is true, contains no female element, but to
balance this, the college of the priestesses of the Sun, which I shall
describe presently, wields considerable powers in the government of
the state. Moreover, the severe restrictions concerning their relations
with the King rest, at least nominally, on religious grounds and would
therefore naturally be less likely to cause resentment. I think
therefore I had better first discuss the existing attitude of my female
subjects towards myself, for on this point I can at least offer some
correct and detailed information, both from personal knowledge and
as the result of inquiries I have from time to time cautiously ventured
to make of the older women, with whom alone I am permitted to hold
social intercourse.
No unimportant part of the religious training which every girl receives
at her mother's knee in Meleager is the Sun Myth, with its
picturesque fables of the Sun-god and his incarnated Child. The
divine nature and mission of the latter are always dwelt on by the
teacher with particular insistence and with due solemnity; and his
sanctity is described as placing him outside the pale of ordinary men
with ordinary passions. And not only this. Should the Child of the
Sun forget the sacred character of his entrusted mission to his
father's people and flout his father's precepts so far as to stoop to
philander with any maiden of his kingdom, not only will the
disobedient monarch incur his divine parent's grave displeasure, but
also a most terrible fate awaits the unhappy object of his attentions.
From this last portion of the advice instilled into the growing female
mind, I conclude that alarming scandals have actually occurred in
the past; and who can marvel at it? But how recent or remote are
these love intrigues in date; and how or where or when they were
detected and punished I am quite ignorant, nor am I ever likely to
receive enlightenment thereon. But it is also in harmony with my
theory of past troubles of this nature that a salutary story (which is by
no means regarded here as a legend) has long been in circulation.
The tale itself is strongly reminiscent of the old Greek myth of Zeus
and Semele, and in Meleager it takes the shape of an intrigue
between a foolish maiden of the people, Anata by name, and the
then reigning Child of the Sun, who fell a victim to her charms or her
advances. For it is gravely related that Anata actually made her way
to the private apartments of the King by stealth. Whether or no she
obtained any satisfaction from her forbidden interview will never be
known, but it is certain her body was found next morning in the royal
bed-chamber charred and almost unrecognisable as the dire result
of her clandestine embraces in the arms of the son of the God of
Fire. To become the mistress therefore of the Sun-child, should the
monarch descend so low as to forget his divine calling, is but the
certain prelude to an ignominious and horrible death; and such a
belief is firmly held by all women dwelling on Meleager. It is also
pronounced dangerous (as it is voted most decidedly immodest) for
any young woman, whether maiden or married, to allow even the
casual glance of the Sun-child to fall full on her face; so that it is
usual for all girls to fling the light veil, or mantilla, which every
Meleagrian woman wears, over her features in the event of her
encountering accidentally the person of the King. This custom,
however, is not an actual regulation, and I have often noticed girls,
especially those of the populace, indulge in a good solid stare as I
have come riding or walking down the streets of the capital, though
sooner or later some pretence of covering the eyes with the veil was
carried out. Amongst the nobility this formal hiding of the face is
more strictly insisted on, if only as a detail of good breeding. From
what I have seen, the young women of Meleager are short, dark and
comely, with fine brown merry eyes, small features, and dark hair. In
extreme youth they are often remarkably pretty and attractive, but
after child-birth they are very liable to lose their elegant symmetry,
and to find what was an agreeable plumpness exchanged for a
rather prominent bulkiness of figure.
I have never yet so much as spoken to a woman below the age of
thirty or thereabouts, and though the fundamental law forbidding my
intimacy with any woman in the pride and beauty of her youth is
quite wise and logical, according both to the letter and the spirit of
Meleagrian state craft, yet it is a rule that presses very cruelly upon
myself. For remember, I do not grow old and languid; my own vitality
is mysteriously renewed at short intervals, and male youth craves
the society and companionship of female youth; whilst also in my
case this natural desire can never diminish with the passing of the
years. In this respect I stand therefore betwixt the devil and the deep
sea, between Scylla and Charybdis. On the one hand, I have to curb
my juvenile longings and tastes which tend rather to grow stronger
and more insistent; whilst on the other, any attempt to circumvent
this ordinance of the hierarchy would not only end in my own
discomfiture, and possibly removal, but would most certainly result in
the miserable fate of any poor favourite of my choice. The story of
silly Anata's disgrace was not invented by the hierarchy merely to
serve as an empty fable, one may be sure of that. I feel convinced,
too, that the palace teems with spies for this very purpose of
thwarting any such intrigue, and though hitherto I have given no
cause even for suspicion, I feel my position most acutely. It is so
false, and I know it to be false, and so do those who have
manœuvred this particular piece of policy concerning their monarch.
When women have once exceeded the age of thirty (which is
considered the child-bearing limit in Meleager), and have
presumably lost all officially suspected attraction in the eyes of the
Child of the Sun, the embargo is removed, though there is never
much intercourse between the King and the middle-aged or elderly
ladies of the nobility. Whenever I honour the country home of one of
my nobles with my presence, all the young women of the household,
married or unmarried, are removed elsewhere, but such as are
above the fixed age of thirty are suffered to remain, though even in
these cases I note that I am seldom left alone with women, no matter
what their age. No doubt the female mind, so strongly imbued in
childhood with the inherent mystical terrors of their monarch, still
shrinks with awe from too close proximity with such a force of
potential danger. Possibly, however, I may err on this point, and in
reality some ancient notion of etiquette unknown to me is being
served by this noticeable self-effacement on the part of the older
women. Of course, the deference wherewith I am treated by the
male folk is intensified in the case of the ladies, who regard me much
in the same light that a bigoted Catholic would regard a tangible
apparition of St Peter or St Paul in their houses.
Politically, women possess no rights, but then no more do the men,
except the handful who compose the executive council, so they
cannot well complain of invidious treatment on this score, even were
they anxious to discover grievances of sex. As with the historic
Prussian queen, their empire admittedly lies in the nursery, for all
children are completely under the charge of their mothers according
to immemorial custom. In the nobility the tacit law seems to be that
the man is master outside the house, whilst the woman is mistress
within doors; and this maxim is generally acted upon throughout all
spheres of social life. Women are exempt from the poll-tax, which is
levied on all males, and indeed no taxes are exacted from women at
all, except in the rare and transitory instances of unmarried
heiresses of landed estates. Whether or no, vague, restless,
unsatisfied aspirations and longings occasionally assail the minds of
some of the younger men I cannot say for certain; but I do feel sure
that the womanhood of Meleager is absolutely satisfied with its
present lot and cannot so much as conceive of any betterment of
existing conditions. The conversations I have had with the wives or
sisters of my hosts at different times were usually of a rather stilted
and uninteresting nature; but I never failed to note their supreme
content and buoyant cheerfulness.
Nevertheless, although women have never been admitted into the
ranks of the hierarchy, and presumably never will be, yet they
possess a species of council of their own sex in the college of the
priestesses of the Sun, who inhabit a large block of buildings
contiguous to the great temple. This institution is based on rules
somewhat similar to those which prevail in the Council of the
Seventy, but it is worked and administered on broader lines, and the
age limit is not so strictly drawn as in the case of the hierarchy. Girls
who have no desire or vocation for matrimony may enter the portals
of this convent (if I may so term it) as novices; nor is the acceptance
of applicants confined to one social class, as is the rule concerning
the probationers of the hierarchy. On the contrary, a fair proportion of
the inmates of this convent are drawn from the middle and lower
classes, and thus the atmosphere of the convent is of a distinctly
democratic type. Even the highest office of all, that of Domina, or
lady abbess, is occasionally attained by a plebeian, for the rules of
election here are carefully compiled so as to secure the choice of the
most popular and capable of the candidates. The senior ladies of the
convent are kept in constant touch with the members of the council,
who frequently apply to the priestesses of the Sun for advice in
various matters of a social and remedial nature, which may be
deemed expedient. Thus all regulations concerning the welfare of
women and children have been carefully scrutinised and approved
by the Domina and her assessors before ever they are enforced by
the officials of the council. But how closely and on what lines the
temple and the convent work together is of course beyond my
knowledge, though it is evident that the two institutions are
conducted in apparent harmony with one another.
XI
It is scarcely fair to offer any comparison between the moral
progress as shown in Meleager and that prevailing on the Earth, and
in any case such a comparison would prove impossible, seeing how
varied and how complex are the many moral systems of the greater
planet. With our numerous nationalities it is only logical there should
result great diversities of opinion on ethics, and we are made to
realise our difficulty in estimating any average sum-total of earthly
morals to bring into the field of comparison. Has not one writer of
note averred that the views of sexual morality held by the phallic
worshippers of old and by the extreme Puritans of to-day rest equally
on a common religious foundation? And has not our British poet of
empire somewhere written that
"The wildest dreams of Kew are the facts of Khatmandù,
And the crimes of Clapham chaste in Martaban"?
In the instance of my own kingdom the many defunct and surviving
systems of the nations of the Earth have all been studied and have
doubtless been partially adapted here and there, so that in a sense
the Meleagrian outlook on morals is extremely interesting, as
affording the result of careful unprejudiced investigation over a wide
space of time. But of course the outcome of these secret researches
and deductions cannot possibly be agreeable or obvious to any one
people or set of thinkers on Earth, for it will be remembered that
whereas the Earth is a congeries of tribes and climates and faiths, so
Meleager is homogeneous, unless one takes into account the colder
and almost unexplored parts of Barbaria. And thus, as the
consequence of careful study for many, many generations by acute
well-trained intellects, a sort of eclecticism has been created here in
the field of morals, as has already arisen in the case of religious
tenets.
Here there are no hard and fast rules on moral behaviour, but each
individual is supposed to be guided by his or her instincts, which it is
considered expedient to depress or encourage, according to the
benefit or damage that may accrue thereby to society at large, or to
the state, if you prefer to regard it as such. The open exhibition of
harmful instincts then is looked on by the ruling caste of Meleager as
an occasion not for punishment but for segregation; such tendencies
in themselves being disregarded so long as they are practised in
secret and kept, as it were, under personal control. And here I am
speaking only of traits and tendencies, not of actual crimes, of fraud
or violence, for the punishment of which there exists a severe code
based apparently on the Mosaic laws. A cold-blooded murder is
repaid by a death penalty, which is carried out privately in the case of
a nobleman, by beheadal in prison of a merchant, and by public
hanging in the case of a plebeian. Crimes of assault are met with
strokes from the lash coupled with a fine; outrages on children are
punished by death. But vile crimes and executions are very rare
indeed, and this highly desirable state of things I attribute to the long
period wherein the rulers of Meleager have been gradually
eliminating the feeble-minded and evil-disposed members of the
community by their careful and judicious system of segregation.
Other cases of wrong-doing of a more venial type are usually met by
a scale of fines, which are intended to compensate the injured party
for any damage he may have incurred; whilst minor instances of
violence or disturbance of the peace are frequently punished by an
order to administer a certain number of lashes there and then in
open court, this penalty being not uncommonly awarded to drunken
or refractory persons belonging to the seafaring, peddling, long-
shore and such humbler sections of the populace.
Thanks again to the past measures taken to repress crime and to
ensure good behaviour, the physical health of the kingdom leaves
almost nothing to be desired. Epidemic diseases are practically
unknown, as are also contagious venereal maladies. It is the
constant, and possibly rather trying and officious, visitations made by
the sanitary inspectors into every homestead, small or great,
patrician or plebeian, which have doubtless helped to induce this
highly commendable condition of affairs. Disease and dirt are the
two evils which are attacked without rest or mercy by the councillors
appointed for their control, and by their equally energetic
representatives. Cleanliness is not reckoned as next to godliness in
Meleager; it is an inherent part of religion itself, and hygienic
regulations are perpetually being enforced upon what is now become
a willing, though no doubt in past times it was an unwilling,
population. I suppose many English Puritans would look askance at
the thermal establishments which exist both in the cities and in the
rural districts, seeing that the two sexes have here opportunities of
studying one another in a nude state; but then, as I have said before,
Meleagrian morals do not exist for morality's sake, but have
evidently been framed for the special purpose of securing a healthy
vigorous race. Early marriage is encouraged, but, paradoxical as it
may appear, large families are not considered desirable; whilst there
is a curious custom which permits of a husband no longer cohabiting
with his wife after she has borne him three children living. I have
heard that this eccentric, and no doubt to many offensive, notion also
prevails in the upper ranks of the civilised Latin races, though
possibly my informant may have been mistaken in his statement. I
gather that such a tacit understanding has its origin in the fear of
over-population, and certainly the limited land surface of Meleager
possessing a desirable climate may plead as a reasonable excuse
for the holding of this whimsical tenet, which seems to savour of the
school of Malthus. Apparently the growth of population in Meleager
is somewhat analogous to that of modern France, and seeing the
high place in which French philosophy and culture are held by the
leading nations of the Earth, the Meleagrians are at least erring in
good company.
Turning to the coarser side of the question of public morals,
prostitution exists, but neither to a great extent nor openly. Those
who can recall the nocturnal conditions of the main London
thorough-fares during the latter part of Queen Victoria's reign would
be agreeably surprised to detect no outward flaunting of vice after
dusk in the streets of Tamarida; and the least tendency to riot or
disturbance is promptly quelled by the military patrols. Not that
licence and debauchery do not abound, for there are, I believe,
plenty of resorts of a certain class in the towns; but the doings of
such places do not rise to the surface, and those who frequent them
dare not offend the quiet of their neighbours.
Meanwhile the priestesses of the Sun are constantly busied with the
ultimate fate of the harlot, and their emissaries are often engaged in
reclaiming girls from a licentious career and in training them to
become useful wives, for such early lapses are held lightly by the
mass of the people. And in not a few instances these "filles de joie"
become wedded to their paramours, and make good mothers. Such
an outlook is of course utterly unmoral to large sections of the
civilised and Christianised nations of Europe and America; but the
Meleagrian view is shared by many other races of the Earth who
have enjoyed a longer and perhaps a better record of civilisation
than have these complacent modern nations whose ancestors were
half-naked savages in the days of the Roman Empire. Universal
chastity, in short, is a feature almost exclusively confined to northern
tribes of barbarians, for whom it has great natural advantages
certainly, for it tends to breed a hardy and prolific race. But I do not
think it can be classed as a genuine virtue in itself, and it always
tends promptly to disappear the moment the trammels of education
and development are assumed. Now the Meleagrians can lay claim
to be an intensely civilised race, whereby I mean their rulers have
been engaged in the study of the arts of peace and progress for
many centuries, and have consequently left behind them the old
barbarian necessity for absolute chastity, though they still recognise
its value as a wholesome ingredient of married family life. For with
marriage chastity in their eyes takes on another aspect, which must
not be confounded with the former, and that is faithfulness. A
faithless wife is very rare indeed in Meleager, and her treatment at
the hands of her neighbours is not enviable.
XII
Religion has already entered so significantly into my narrative that I
feel I must apologise for a special dissertation on this subject. Yet I
have never so far described the exact nature or scope of the
Meleagrian faith which may be said to permeate and regulate the
whole private and public existence of the people.
The inhabitants of Meleager—and in the ensuing statements, of
course, I always except the hierarchy—are worshippers of the Sun,
who is their sole deity. He is visible to them for a large portion of
almost each day; he is tangible, in so far as they can feel the warmth
of his beams; he is alive and in constant motion, as they watch him
"ride the heavens like a horse" and disappear into the waters of the
western sea only to uprear again next morning above the eastern
horizon. As in the old Greek mythos, the Sun is popularly supposed
to drive his golden chariot with its flaming wheels and with its yoke of
fretting stallions across the dome of heaven, till finally god and car
alike pass over the containing rim of the Meleagrian world. Below the
flat surface of the land and sea the Sun-god inhabits a vast palace,
whose splendours far exceed anything known to men. Here he rests
after his daily labours amongst his numerous progeny, and refreshes
himself after his late exertions undertaken solely for the benefit of the
favoured race, that in the illimitable past he created in his own
image. The firmament is his field of action; the space below the
ground is his haven of retirement. At night the dome of heaven shorn
of his effulgent presence is lighted only by the sparkling stars;
"jewels of the Sun," as they are termed in Meleagrian parlance; or
else the great vacant arc is illumined by the sickly lustre of the Moon.
For the Moon stands to the Meleagrian mind, as it did largely to the
antique and mediæval imagination, for all that is uncanny and
malign. Few Meleagrians will walk abroad in clear moonlight, if they
can reasonably avoid so doing; and in the many tales and legends
that are current the Moon in her various phases and with her evil
influence always occupies a prominent place. The oldest legend
concerning the Moon, that is a legend parallel with such theories as
the origin of the rainbow or the story of the Ark on Mount Ararat of
the Jewish Pentateuch, relates how in the days of chaos there were
two Suns, rivals, who fought one another for the possession of the
beautiful world of Meleager; and that after a titanic combat, wherein
the heavens thundered and the mountains belched forth fire and
smoke, and the waters tossed and hissed furiously, the benign Sun
conquered and slew the opposing deity, whose dead body still floats
abroad in the sky, wherein it serves as an eternal trophy to the
prowess of the victor. In the popular imagination however the corpse
of the vanquished Moon is not wholly impotent for ill. A scintilla of
mischievous vitality is still believed to lurk in its form, during the
hours of the night, what time the Sun himself is absent from the
heavens. The average Meleagrian therefore has a peculiar dread of
the night, and of a moonlit night in a special degree. The practice of
magic, both of the black and white types, is fairly common in all
ranks of Meleagrian society, and its preparations and philtres are
always popularly associated with the period of the Moon's fulness,
when that deity's surviving spark of life is deemed most active.
The cult of the Meleagrians for the Sun not only recognises his vital
warmth and fructifying properties, but also attributes to him the
gathering or dispersal of the clouds which drop the refreshing rain
upon the thirsty soil and swell the opening buds of tree and plant.
The winds are also under the Sun's control, and are apparently
regarded as his offspring, who sometimes disobey their august
parent's injunctions, and either sportively or maliciously vex the
people of Meleager with unwelcome gales that imperil the fisher-folk
at sea, and injure the springing crops on land. But speaking broadly,
the Meleagrian is of St James's opinion that "every good gift and
every perfect gift is from above, and cometh down from the Father of
Lights with whom is no variableness neither shadow of turning." And
in truth the unchangeable benignity and faithfulness of the Sun-god
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

You might also like