Download PDF Jump start node js get up to speed with node js in a weekend 1st edition nguyen don ful

Page 1


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

Visit to download the full and correct content document: https://textbookfull.com/product/jump-start-node-js-get-up-to-speed-with-node-js-in-aweekend-1st-edition-nguyen-don/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Jump Start CoffeeScript Get Up to Speed With CoffeeScript in a Weekend 1st Edition Castledine Earle

https://textbookfull.com/product/jump-start-coffeescript-get-upto-speed-with-coffeescript-in-a-weekend-1st-edition-castledineearle/

Fullstack Node js The Complete Guide to Building Production Apps with Node js Davit Guttman

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

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-developmentlearn-the-fundamentals-of-node-js-and-deploy-and-test-node-jsapplications-on-the-web-1st-edition-andrew-mead/

RESTful Web API Design with Node js 10 Learn to create robust RESTful web services with Node js MongoDB and Express js 3rd Edition English Edition Valentin Bojinov

https://textbookfull.com/product/restful-web-api-design-withnode-js-10-learn-to-create-robust-restful-web-services-with-nodejs-mongodb-and-express-js-3rd-edition-english-edition-valentin-

Instant Node js Starter 1st Edition Teixeira Pedro

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

Full Stack JavaScript Learn Backbone js Node js and MongoDB Mardan Azat

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

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-serverside-development-with-node-10-made-easy-fourth-edition-editiondavid-herron/

Pro Express js Master Express js The Node js Framework For Your Web Development Mardan Azat

https://textbookfull.com/product/pro-express-js-master-expressjs-the-node-js-framework-for-your-web-development-mardan-azat/

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

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

JUMP START NODE.JS

BY DON NGUYEN

Jump Start Node.js

Copyright © 2012 SitePoint Pty. Ltd.

Product Manager: Simon Mackie

Technical Editor: Diana MacDonald

Expert Reviewer: Giovanni Ferron

Notice of Rights

Indexer: Fred Brown

Editor: Kelly Steele

Cover Designer: Alex Walker

All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.

Notice of Liability

The author and publisher have made every effort to ensure the accuracy of the information herein. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors and SitePoint Pty. Ltd., nor its dealers or distributors will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software or hardware products described herein.

Trademark Notice

Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark.

Published by SitePoint Pty. Ltd.

48 Cambridge Street Collingwood VIC Australia 3066

Web: www.sitepoint.com

Email: business@sitepoint.com

ISBN 978-0-9873321-0-3 (print)

ISBN 978-0-9873321-1-0 (ebook)

Printed and bound in the United States of America

About the Author

Don began his programming career with strongly typed, object-oriented languages such as Java and C++. He used his engineering training to build real-time trading systems designed to be scalable and fault tolerant.

While his first introduction to functional programming was somewhat of a shock to the system, the beauty and elegance of weakly typed dynamic languages such as Python and Ruby shone through. Don has programmed in a variety of web environments including ASP, PHP, and Python, but feels that Node.js is foremost at handling the modern demands of the real-time web.

About the Expert Reviewer

Giovanni Ferron is a web developer currently living in Melbourne, Australia. He has worked for major media companies such as MTV and DMG Radio Australia, and co-founded the website Stereomood.com.1 A couple of years ago, he fell in love with Node.js and has been spending his nights programming in JavaScript ever since.

About SitePoint

SitePoint specializes in publishing fun, practical, and easy-to-understand content for web professionals. Visit http://www.sitepoint.com/ to access our blogs, books, newsletters, articles, and community forums.

1 http://stereomood.com

This book is dedicated to my Mum and Dad.

To my Dad for his endless patience in driving me to rowing, martial arts, and tennis practice, and for his never-ending support.

To my Mum for cooking dinner with one hand and sketching out the basics of object-oriented programming and database normalization with the other

Table of Contents

Preface

Who Should Read This Book

What’s in This Book

Where to Find Help

The SitePoint Forums

The Book’s Website

The SitePoint Newsletters

Your Feedback

Chapter 6 Backbone

Preface

One of the difficulties I had when trying to learn Node.js was how to get started. The references that I found either dealed with quasi-academic topics such as datagrams and event emitters, or else myopically focused on a topic without regard for the big picture. This book takes you through the complete process of building an application in Node.js. It starts with the canonical “Hello World” example, and goes on to build a real-time web application capable of sending trading information to thousands of connected clients.

What make Node.js different? First, it provides a unified language between the back end and front end. This means that all your thinking can be in a single language, with no cognitive overhead when switching from front end to back. Furthermore, it allows for shared code libraries and templates. This opens up a lot of interesting possibilities, the surface of which is just beginning to be properly explored.

Second, it’s fast. One of the common complaints of interpreted languages such as PHP, Python, and Ruby is speed. Jason Hoffman, CTO of Joyent, has discussed how Node.js is at the point where its performance can break operating systems. A single core with less than 1GB of RAM is capable of handling 10GB of traffic and one million connected end points. Combining 24 of these into a single machine produces an overall level of throughput that exceeds the capacity of operating systems and TCP/IP stacks. In other words, with a properly designed application it’s not Node.js that’s the bottleneck it’s your operating system.

Third, its nonblocking architecture is made for the real-time web. JavaScript was chosen as a language because it’s based on nonblocking callbacks and has a very small core API. This means it was possible to build the entire Node.js ecosystem around nonblocking packages, of which there are currently in excess of ten thousand. The end result is a platform and ecosystem that architecturally fits perfectly with the modern demands of the real-time web.

I trust by now that you’re excited by the possibilities of what Node.js can do for your real-time application. By the end of this book, I’m confident that you’ll have the skills to be able to start dissecting and solving all but the most esoteric of problems. There is no greater joy in software than solving a complicated task and thinking at the end of it, “That was all I had to do!” It is one I’ve experienced many

times working with Node.js, and it’s my hope that you enjoy the same satisfaction both throughout the book and in using Node.js to solve your real-world problems.

Who Should Read This Book

This book is aimed at two target audiences. You might be a front-end engineer who is interested in looking at server-side development. An existing knowledge of JavaScript will prove useful, even if you are unfamiliar with certain server-side engineering techniques. Rest assured that by the end of the book, the topic will be covered in sufficient detail for you to know how to apply your front-end skills to back-end problems.

The second potential reader is the server-side engineer who uses another language such as PHP, Python, Ruby, Java, or .NET. The main benefit you’ll derive is seeing how your existing architectural, design, and pattern knowledge is applied to the world of Node.js. You may have little to no knowledge of JavaScript, but this should pose no big hindrance. By design, it’s an easy language to learn, and we will have covered many examples of both its syntax and idiosyncratic features by the end of the book.

What’s in This Book

This book comprises the following seven chapters.

Chapter 1: Coming to a Server Near You

Node.js is introduced and its features and benefits explained. We then build a simple application to introduce Node.js. The application sends data from a form to MongoDB, a NoSQL database.

Chapter 2: Let’s Get Functional

This chapter introduces programming with Node.js in a functional style. We’ll build a stock exchange trading engine that’s capable of accepting orders and matching trades.

Chapter 3: Persistence Pays

Here we explore MongoDB. I’ll explain the use cases of MongoDB and how it compares to traditional SQL databases. We’ll then look at the MongoDB query language and show how it can be integrated with your Node.js projects.

Chapter 4: Beautifying with Bootstrap

Bootstrap is a front-end framework from Twitter that makes it easy to build professional-looking sites. We’ll look at some of the most common widgets and use them to build a login screen and stock portfolio tracker.

Chapter 5: The Real-time Web

In this chapter we examine Socket.IO. We’ll see how learning one simple API can allow real-time communication across a range of projects without needing to worry about browser versions or communications protocols.

Chapter 6: Backbone

We’ll discuss how frameworks are useful in managing client-side JavaScript in this chapter. We’ll then show how Backbone.js can be incorporated into your project by updating trades in the browser in real time.

Chapter 7: Production

In the final chapter, we’ll look at the main differences between a development and production environment. We’ll cover various deployment options before getting our application deployed and running live!

Where to Find Help

Node.js represents a paradigm shift in web development, providing a unifying language all the way from the front end to the back end. It has experienced a boom in popularity on GitHub, so chances are good that by the time you read this, some minor detail or other of the Node.js platform will have changed from what’s described in this book. Thankfully, SitePoint has a thriving community of JavaScript developers ready and waiting to help you out if you run into trouble, and we also maintain a list of known errata for this book that you can consult for the latest updates.

The SitePoint Forums

The SitePoint Forums1 are discussion forums where you can ask questions about anything related to web development. You may, of course, answer questions, too. That’s how a discussion forum site works some people ask, some people answer and most people do a bit of both. Sharing your knowledge benefits others and strengthens the community. A lot of fun and experienced web designers and de-

1 http://www.sitepoint.com/forums/

velopers hang out there. It’s a good way to learn new stuff, have questions answered in a hurry, and just have fun.

The JavaScript & jQuery Forum2 is probably the best place to head to ask any questions.

The Book’s Website

Located at http://www.sitepoint.com/books/nodejs1/, the website that supports this book will give you access to the following facilities:

The Code Archive

As you progress through this book, you’ll note a number of references to the code archive. This is a downloadable ZIP archive that contains each and every line of example source code that’s printed in this book. If you want to cheat (or save yourself from carpal tunnel syndrome), go ahead and download the archive.3

Updates and Errata

No book is perfect, and we expect that watchful readers will be able to spot at least one or two mistakes before the end of this one. The Errata page on the book’s website will always have the latest information about known typographical and code errors.

The SitePoint Newsletters

In addition to books like this one, SitePoint publishes free email newsletters such as the SitePoint newsletter, JSPro, PHPMaster, CloudSpring, RubySource, DesignFestival, and BuildMobile. In them you’ll read about the latest news, product releases, trends, tips, and techniques for all aspects of web development. Sign up to one or more of these newsletters at http://www.sitepoint.com/newsletter/.

Your Feedback

If you’re unable to find an answer through the forums, or if you wish to contact SitePoint for any other reason, the best place to write is books@sitepoint.com. We have a well-staffed email support system set up to track your inquiries, and if our

2 http://www.sitepoint.com/forums/forumdisplay.php?15-JavaScript-amp-jQuery

3 http://www.sitepoint.com/books/nodejs1/code.php

support team members are unable to answer your question, they’ll send it straight to us. Suggestions for improvements, as well as notices of any mistakes you may find, are especially welcome.

Friends of SitePoint

Thanks for buying this book. We really appreciate your support! We now think of you as a “Friend of SitePoint,” and so would like to invite you to our special “Friends of SitePoint” page. 4 Here you can SAVE up to 43% on a range of other super-cool SitePoint products, just by using the password: friends.

Online Quiz

Once you’ve mastered Node.js, test yourself with our online quiz. With questions based on the book’s content, only true Node.js ninjas can achieve a perfect score. Head on over to http://quizpoint.com/#categories/NODE.JS.

Acknowledgments

I’d like to thank the wonderful team at SitePoint for guiding me through the process of publishing my first book: to Simon Mackie for patiently answering all my questions and keeping everything on track; to Giovanni Ferron for reviewing my code and pointing out bugs; to Diana MacDonald for ensuring clarity in my code; to Kelly Steele for keeping my English stylistically and grammatically correct; and to Alex Walker for the wonderful cover art.

To my longtime friends, Jarrod Mirabito and Andrew Prolov: thanks for helping review my initial work long before it was even a book proposal. To my flatmate, Angelo Aspris: thanks for patiently accepting “busy writing” as an excuse for long stretches of absenteeism. To Andy Walker: thanks for keeping the flame of entrepreneurship burning brightly. To my lifelong friend Chuong Mai-Viet: thanks for dragging me away from the desk on bright and sunny days to keep my golf handicap down and my Vitamin D intake up.

4 http://sitepoint.com/friends

Conventions Used in This Book

You’ll notice that we’ve used certain typographic and layout styles throughout this book to signify different types of information. Look out for the following items.

Code Samples

Code in this book will be displayed using a fixed-width font, like so:

<h1>A Perfect Summer's Day</h1>

<p>It was a lovely day for a walk in the park. The birds were singing and the kids were all back at school.</p>

If the code is to be found in the book’s code archive, the name of the file will appear at the top of the program listing, like this:

example.css

.footer { background-color: #CCC; border-top: 1px solid #333; }

If only part of the file is displayed, this is indicated by the word excerpt:

example.css (excerpt)

border-top: 1px solid #333;

If additional code is to be inserted into an existing example, the new code will be displayed in bold:

function animate() { new_variable = "Hello"; }

Also, where existing code is required for context, rather than repeat all the code, a ⋮ will be displayed:

function animate() { ⋮ return new_variable; }

Some lines of code are intended to be entered on one line, but we’ve had to wrap them because of page constraints. A ➥ indicates a line break that exists for formatting purposes only, and should be ignored.

URL.open("http://jspro.com/raw-javascript/how-to-create-custom-even ➥ts-in-javascript/");

Tips, Notes, and Warnings

Hey, You!

Tips will give you helpful little pointers.

Ahem, Excuse Me …

Notes are useful asides that are related but not critical to the topic at hand. Think of them as extra tidbits of information.

Make Sure You Always …

… pay attention to these important points.

Watch Out!

Warnings will highlight any gotchas that are likely to trip you up along the way.

Chapter1

Coming to a Server Near You

“You see things and you say, ‘Why?’ But I dream things that never were, and I say, ‘Why not?’”

Why Node.js?

If a picture speaks a thousand words, what would it take to speak a thousand pictures? Or for that matter, an infinite number of pictures? My first introduction to Node.js was through WordSquared,1 seen in Figure 1.1. This is an online, real-time, infinite game of Scrabble built using the same technologies that we’ll discuss in this book. As soon as I set eyes on the game, I had to find out more about the technology behind it, and I hope you feel the same.

What’s incredible about the game is that it was prototyped in just 48 hours as part of Node.js Knockout.2 Bryan Cantrill, VP of Engineering at Joyent (which manufactures Node.js) has said that when doing things in Node.js, you sometimes get the feeling of “Is this it? Surely it needs to be more complicated.” This is a sentiment

1 http://wordsquared.com/

2 http://nodeknockout.com/

I share. Node.js is a joy to work with, and I intend to share that with you through the code we’ll write throughout this book.

Figure 1.1. WordSquared: a way to examine Node.js in action

Node.js is a server-side JavaScript platform that consists of a deliberately minimalist core library alongside a rich ecosystem. It runs atop the V8 JavaScript engine, which makes it very fast thanks to the talented engineers at Google. JavaScript is popular on the client side, but it was chosen as the target language primarily for engineering considerations, the details of which will be discussed as the chapter unfolds.

The home page of Node.js describes it thus:

“Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.”

http://nodejs.org/

This may seem cryptic to newcomers, but it succinctly summarizes some of the key strengths of Node.js and is worth exploring in more detail. People are often taken aback when they hear that JavaScript is the targeted programming language. That’s because there’s a perception in the programming community that JavaScript is not a “real” language such as C, C++, or Java. Yet JavaScript did have its genesis as an interpreted language for the browser; the “Java” part of the name was actually chosen to capitalize upon the perceived popularity of the Java programming language at the time.

Since its humble beginnings, JavaScript has proliferated and is now supported in every major web browser, including those on mobile devices. Not only is it a popular language, but the tools and frameworks currently available for it make it qualify as a powerful engineering tool. JavaScript as a server-side platform supports continuous integration, continuous deployment, connections to relational databases, serviceoriented architecture, and just about every other technique available to its more well-established brethren.

In conjunction with Google’s V8 JavaScript engine, it is now extremely fast; in fact, it’s several times faster than other scripted languages such as Ruby and Python. Against Python3, JavaScript V8 Engine has a median benchmark 13 times as fast with a roughly similar code size.3 Against Ruby 1.9, the median benchmark is eight times as fast.4 These are incredible benchmarks for a dynamic language, and are due in no small part to V8 optimizations such as compilation into machine code pre-execution.

On Benchmarking

Benchmarking is an intricate topic,5 and the numbers above should be taken with the proverbial grain of salt. Whenever any discussion of benchmarking arises, it is generally qualified with “it depends.” The main purpose of discussing the benchmark was to dispel any misconception of JavaScript being inherently slow.

The official description talks about the event-driven, non-blocking I/O model. Traditionally, programming is done in a synchronous manner: a line of code is executed, the system waits for the result, the result is processed, and then execution resumes. Sometimes waiting for the result can take a long time; for example, reading from a database or writing to a network.

In languages such as Java and C#, one solution is to spawn a new thread. A thread may be thought of as a lightweight process that performs tasks. Threaded programming can be difficult because multiple threads can be trying to access the same resource concurrently. Without dissecting the intricacies of multi-threaded programming, you can imagine it would be disastrous for one thread to be incrementing a counter while another thread is decrementing the counter at the same time.

3 http://shootout.alioth.debian.org/u32/benchmark.php? test=all&lang=v8&lang2=python3

4 http://shootout.alioth.debian.org/u32/benchmark.php? test=all&lang=v8&lang2=yarv

5 http://shootout.alioth.debian.org/dont-jump-to-conclusions.php

JavaScript approaches the problem differently. There is only ever a single thread. When doing slow I/O operations such as reading a database, the program does not wait. Instead, it immediately continues to the next line of code. When the I/O operation returns, it triggers a callback function and the result can be processed. If the mechanics of this seems slightly counterintuitive, rest assured that by the end of the book it will be second nature, because we’ll be seeing this pattern over and over again. Node.js offers a simple, fast, event-driven programming model well-suited to the asynchronous nature of modern-day web applications.

Strengths and Weaknesses

Node.js is not a panacea. There is a certain class of problems in which its strengths shine through. Computer programs can be generally classified according to whether they are CPU bound or I/O bound. CPU bound problems benefit from an increase in the number of clock cycles available for computation. Prime number calculation is a good example. Node.js, however, is not designed to deal with these CPU bound problems. Even before Node.js formally existed, Ryan Dahl proposed the following:6

“There is a strict requirement that any request calculates for at most, say, 5ms before returning to the event loop. If you break the 5ms limit, then your request handler is never run again (request handlers will be tied to a certain path/method, I think). If your uploaded server-side JavaScript is stupid and is blocking (… it calculates the first 10,000 primes) then it will be killed before completion.

Web developers need this sort of environment where it is not possible for them to do stupid things. Ruby, Python, C++, [and] PHP are all terrible languages for web development because they allow too much freedom.”

I/O bound problems are alleviated by increased throughput in I/O such as disk, memory, and network bandwidth, and improved data caching. Many problems are I/O bound, and it’s in this domain that Node.js truly shines. Take, for example, the

6 http://four.livejournal.com/963421.html

C10K problem,7 which poses the dilemma of how to handle ten thousand or more concurrent connections for a web server. Some technology platforms are ill-equipped for managing this type of capacity and require various patches and workarounds. Node.js excels at this task because it’s based on a nonblocking, asynchronous architecture designed for concurrency.

I hope I’ve whetted your appetite; it is now time to begin.

On Speed

The book’s core project involves building a real-time stock market trading engine that will stream live prices into a web browser. The more inquisitive among you may ask, “Shouldn’t a stock market trading engine be built using a language such as C for faster-than-light, jaw-dropping speed?” If we were building a stock market engine for actual trading, my answer would be “Yes.”

The main goal of this book is to transfer the skill set rather than the actual project into the real world. There is a narrow domain of “hard” real-time applications such as a stock exchange where specialized software and hardware are required because microseconds count. However, there is a much larger number of “soft” real-time applications such as Facebook, Twitter, and eBay where microseconds are of small consequence. This is Node.js’s speciality, and you’ll understand how to build these types of applications by the end of this book.

In the Beginning

Let’s run through installing Node.js, setting up a web framework, building a basic form page, and connecting to a database.

Installation

It is possible to install Node.js from the raw source code, but it’s much simpler to install using a package manager.

Go to https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager and follow the instructions for your particular distribution. There are currently instructions for Gentoo, Debian, Ubuntu, openSUSE and SLE (SUSE Linux Enterprises),

7 http://en.wikipedia.org/wiki/C10k_problem

Fedora, and RHEL/CentOS, as well as several other Linux distributions. Windows and Mac OS X instructions are also available.

After installation, type node at the command line to bring up the read-eval-print loop (REPL). You can test your installation by typing:

console.log('Hello world')

You should receive: Hello world undefined

If you did, congratulations! You have just written your first Node.js program. The console always prints out the return type. This is why Hello world is followed by undefined. Now that you’ve written the canonical Hello world program, I’m happy to inform you that it will be the first and last boring program you’ll see in this book.

To prove my point, we’ll now jump straight in and build an authentication module to verify usernames and passwords using cloud-based NoSQL technology. (If you’re scratching your head and wondering what this means, don’t worry all will be revealed shortly!)

So what is cloud-based NoSQL technology, and why should you care? There’s been a lot of hype around cloud-based technology. For our purposes, cloud technology is useful because it allows our applications to scale: additional virtual servers can be brought online with just a few mouse clicks.

The NoSQL movement is relatively recent and, as such, it is difficult to arrive at a comprehensive definition of what the technology encompasses. Broadly, it can be thought of as a family of database technologies built for handling large masses of unstructured and semi-structured data. Companies such as Google, Amazon, and Facebook make extensive use of NoSQL technology to house the vast quantities of data generated by their users.

For this book, we will be using MongoDB as our NoSQL database for reasons that will be fleshed out in more detail in Chapter 3. MongoDB is a mature and scalable document-oriented database that has been deployed successfully in enterprise en-

vironments such as foursquare and craigslist.8 A document-oriented database is a database where the traditional database row is replaced with a less structured document, such as XML or JSON. MongoDB allows ad hoc queries and so retains much of the flexibility that SQL offers. I’ve chosen MongoLab9 as a cloud provider for our stock monitoring application because it has a generous free hosting plan in place.

Assembling the Pieces

The first step is to go to MongoLab, seen in Figure 1.2, and sign up an account. Then click on Create New next to Databases. Leave the cloud provider as Amazon EC2 and select the free pricing plan. Choose a database name, a username, and password.

Now we’ll set up the web framework. Node.js provides a built-in, bare-bones HTTP server. Built on top of this is Connect, a middleware framework that provides support for cookies, sessions, logging, and compression, to name a few.10 On top of Connect is Express, which has support for routing, templates (using the Jade templating engine), and view rendering.11 Throughout this book we’ll predominantly use Express.

8 http://api.mongodb.org/wiki/current/Production%20Deployments.html

9 http://mongolab.com

10 http://www.senchalabs.org/connect/

11 http://expressjs.com/guide.html

Figure 1.2. Signing up to MongoLab

We use the -g switch to indicate that the package should be installed globally and @2.5.8 to indicate the version we’ll use in this book.

Global versus Local

On the official Node.js blog, sparing use of global installs is recommended.12 The guideline is to use a global install if the package needs to be accessed on the command line, and a local install if it needs to be accessed in your program. In some cases such as Express where both are required it’s fine to do both.

An application with basic default options can be created using this command: express authentication

You should see output similar to the following:

create : authentication create : authentication/package.json

dont forget to install dependencies: $ cd authentication && npm install

To explain the last line ($ cd authentication && npm install), npm install will install packages according to the dependencies specified in package.json. This is a plain-text file that specifies package dependencies in JavaScript Object Notation. For this project, modify package.json to contain the following text: chapter01/authentication/package.json (excerpt) { "name": "authentication" , "version": "0.0.1" , "private": true , "dependencies": { "express": "2.5.8" , "jade": "0.26.1"

12 http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/

Avoiding Dependency Hell

Instead of a particular version number, it’s possible to specify “*” , which will retrieve the latest version from the repository While it may be tempting to always work with the latest version, just because your application is compatible with one version, it in no way guarantees that it will still be compatible with the next. I recommend always stating the version number at the very least. Even this is no guarantee of correctness. If you use a package that employs the “*” syntax, you will run into a similar problem. For a more robust solution, I recommend you look into Shrinkwrap.13

These dependencies can then be installed by changing to the authentication directory (cd authentication) and typing npm install. Then type node app, and after navigating to http://localhost:3000 in your browser, you should see the message, “Welcome to Express.” Easy, wasn’t it?

A Basic Form

The next step is to create a basic form to post data to the server. With a web server such as Apache, you’d normally place a file into a directory to be served to the user. Node.js is deliberately minimalist, with very little that is automatically done. If you wish to read a file from the disk, you’ll need to explicitly program it. Kill your app and, at the top of app.js, add the fs dependency to allow reading from the file system. Then add the /form route:

chapter01/authentication/app.js (excerpt) var express = require('express') , routes = require('./routes') , fs = require('fs'); ⋮ // Routes app.get('/', routes.index);

13 http://blog.nodejs.org/2012/02/27/managing-node-js-dependencies-with-shrinkwrap/

app.get('/form', function(req, res) { fs.readFile('./form.html', function(error, content) { if (error) { res.writeHead(500); res.end(); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(content, 'utf-8'); } }); });

The above listing has several important features.

This line handles all the routing to /form. Whenever anybody makes a request to http://localhost:3000/form, Express captures the request and it is handled by the code within.

This line attempts to read form.html from the file system and serve the HTML file. If there’s an error, a 500 response will be sent back to the browser.

Callback Functions

This is the first time we’ve broached callback functions, which might be tricky for those starting from other languages. As an example, type the following into a file named cb.js:

setTimeout(function() {console.log('first or second');} , 500); console.log('we will see');

Run node cb and note the text order. The first line sets a timeout for a function to be executed in 500ms. The program immediately resumes execution, which is why we will see is printed before first or second.

In Node.js, everything is asynchronous by design, so only your own code will block a process. The first line in this code sample could be any I/O operation including reading and writing from databases and networks. In every instance, nothing I/O-related will block and the rest of your program will immediately ex-

Another random document with no related content on Scribd:

Turkey would at that time undoubtedly have been partitioned, had Austria been willing to follow the numerous gentle hints to join the alliance of the emperors, who imagined themselves able to make their will the right and law of all nations; or if Napoleon had not found it inconsistent with his plans to bring on at an unfavourable moment a new war with Austria, which he clearly foresaw in 1808. The Russians, in the mean time, remained, throughout the whole of the year 1808, in quiet possession of the provinces which had been previously evacuated by them, and ruled not only in them, but extended their dominion as far as Belgrade, for the new prince of Servia was likewise under Russian protection. The army under the command of the grand vizir, which lay at Adrianople during the winter of 1807-1808, dwindled, during the continuance of the truce of Slobozia, to a few thousand men, because, according to ancient custom, the janissaries returned to their homes in winter; it again increased, however, in the beginning of summer. Bairaktar’s army, which was organised on the new European principle, was computed at from twenty to thirty thousand men; it remained on the Danube till its leader, at length, resolved to put an end to the anarchy prevailing in Constantinople. He deposed Mustapha IV, who supported the faction of the janissaries, and placed his brother, Mahmud, on the throne. Bairaktar perished, however, in an insurrection (November 14th), and Mahmud, too, would have been murdered, had he not been the last scion of the imperial family. But he was compelled entirely to change his ministry, and to resign the government into the hands of those who enjoyed the favour of the ulemas and the janissaries.

During the disturbances in the internal affairs of the Turkish Empire, the foreign relations continued the same as they were in the year 1807, immediately after the truce of Slobozia. When Napoleon’s plan of removing the negotiations respecting a peace between the Russians and the Turks to Paris failed of success, he found it advisable, in consequence of an impending war with Austria, to give the Turks into the hands of the Russians. One of the chief causes of the war between France and Austria in 1809 was the close union between the latter power and England in reference to Turkish affairs, which appeared in the co-operation of Lord Paget and Baron von

Stürmer, the English and Austrian ambassadors in Constantinople. It was the Austrians who mediated the peace between England and the Porte of the 5th of January, 1809, after the conclusion of which the Turks refused to cede Moldavia and Wallachia to the Russians, at the congress of Jassy, as they had formerly done at Bucharest. This led to a new war, of which we shall have to speak hereafter.

CONGRESS OF ERFURT (1808 A.D.)

In consequence of the complete stoppage of trade which followed the declaration of war in 1807, Russia suffered much more severely than England, and the Russian magnates, supported by the aversion of the emperor’s mother to Napoleon, were very far from showing that good-will to the French which their emperor manifested for Napoleon and his representatives. This was soon experienced by Savary, duke of Rovigo, who, though overloaded with marks of politeness by the emperor, in reality proved unable to make any way at the court of St. Petersburg. Caulaincourt, duke of Vicenza, was afterwards deceived for some years by appearances, and by Alexander’s masterly art of dissimulation; but Napoleon soon came to experience in Spain that the personal proofs of friendship exhibited by the emperor were by no means always in accordance with the Russian policy. The emperor Alexander himself, for example, on the urgent request of Caulaincourt, acknowledged Joseph Bonaparte as king of Spain; whilst Strogonov, the Russian ambassador in Madrid, alleged that he had no instructions to that effect, and corresponded with the insurgents. In the same way, Admiral Siniavin, who, on the breaking out of war with England, had taken refuge in Lisbon with nine ships of the line and a frigate, not only refused to render any assistance to Marshal Junot, who was threatened in that city by the English, but even to make a demonstration as if he were prepared to assist him. The manner in which he afterwards capitulated, on the 3rd of September, 1808, to Admiral Cotton, who caused his ships to be taken to England, might indicate a very different disposition, especially as the ten ships were afterwards given back.

[1808 ]

There was, indeed, no want of interchange of civilities between the two emperors. Whoever compares the attentions and marks of regard which have been recorded as shown by the one to the other with the secret intrigues which they were at the same moment weaving against each other in Turkey and Spain, and with the open enmity which was shown as early as 1811, will learn from such a comparison what is the real worth of diplomatic and princely friendships. The emperor of Russia made presents to his imperial brother of vessels and ornaments of malachite and other precious stones, which the latter exhibited in the Salon du Prix in the Tuileries, in order to be able to boast of the friendship of the emperor of Russia in presence of the circles of the faubourg St. Germain. Busts of Alexander were manufactured in the imperial porcelain manufactory at Sèvres, and were everywhere to be seen in the palace and rooms of the imperial family. All who had access to the court, or wished to make themselves agreeable to the emperor, found it necessary to purchase these ornaments, and place them conspicuously in their houses. The friendship was so intimate that one of the emperor of Russia’s adjutants accompanied the emperor of the French when he went to Bayonne to set aside the whole reigning family of Spain. This adjutant, however, was the same Tchernitchev who was engaged in constantly travelling backwards and forwards between St. Petersburg and Paris, who surrounded Napoleon, in spite of all his police, with a net of Russian espionage, and bribed all the employés who were venal in order to obtain papers. He intrigued with ladies to elicit secrets from them; and finally, in 1812, he even purchased a copy of the plan of operations for the war, when it was too late to change it.

Napoleon knew that Austria was thinking of taking advantage of the general discontent and the secret associations in Germany to frustrate the plans of France and Russia with respect to Poland and Turkey; he was, therefore, very desirous of assuring himself once more of the Russian emperor before his journey to Spain. This design was a cause of great anxiety to the very numerous partisans of the English and Prussian policy at the Russian court, when the question was raised of a conference between the two emperors in Erfurt. Von Schladen, the friend of the minister von Stein, therefore

presented a memorial to the emperor of Russia, shortly before his departure to Erfurt on the 7th of September, 1808, in which Alexander was forewarned of all that would take place there. From this it may be seen that the emperor of Russia was continually receiving secret counsel and warning from the enemies of the French, and that he played his part in Erfurt more ably than Napoleon, from whom he separated, as even the French writers report, with all the outward signs of indescribable friendship and esteem, but inwardly full of distrust. Von Schladen says very freely to the emperor, that he had given him the advice laid down in his memorial, “in order that he might see through the sophisms, falsehoods, and deceptions which were prepared for him by Napoleon, and awaited him in Erfurt.”

On his way to the congress, the emperor visited the king and queen of Prussia in Königsberg, and arrived on the 26th of September in Weimar, where his brother Constantine had been staying since the 24th. On the 27th Napoleon entered Erfurt, and at one o’clock drove out a distance of several miles from the town to meet the emperor of Russia, who was coming from Weimar. Our modest object does not permit us to incorporate in our prose the poetry of the subsequent festivities, nor in glowing language to extol the skill displayed by the masters of the ceremonies. That splendour enough was exhibited in Erfurt may be sufficiently gathered from the fact that the four vassal-kings of the confederation of the Rhine, thirty-four princes, twenty-four ministers of state, and thirty generals, were by express command to summon up for the occasion everything which imagination could suggest in the way of courtly splendour and extravagance. Talma and the Parisian company of actors had been sent to Erfurt, to act, as Napoleon said, before a pit of kings. Two armchairs were placed for the two emperors, whilst the other rulers sat behind them on common chairs. We know not what truth there was in the story, which was at that time in every mouth, and related in all the French works written for effect, that the emperor Alexander, whilst Talma was being applauded on the stage, played his own part with Napoleon in the pit in quite as masterly a manner. The latter, amidst applause, pronounced the following line:

The friendship of a great man is a favour of the gods. when the emperor seized Napoleon’s hand, made a profound bow, and feelingly exclaimed: “That I have never more truly felt than at the present moment.” The festivities continued from the 27th of September till the 14th of October, and furnished to the Germans the most melancholy spectacle of their princes and nobles conducting themselves publicly, not only as slaves of Napoleon, but even as servants and flatterers of all his generals and courtiers.

In order to flatter the emperor of Russia, Napoleon acted as if he had been influenced by Alexander’s application in favour of Prussia; but in reality, oppressed the king and his subjects afterwards just as before. He profited by Alexander’s admiration and friendship to make a show of his pretended willingness to conclude a peace with England. Though he had written three times directly to the king of England, and had always been referred to the minister, he nevertheless prevailed upon Alexander to unite with him in signing another letter addressed to King George. The result was such as might have been foreseen; the object, however, was attained: the letters and answers were printed, and officially commented upon in the journals.

The negotiations were carried on personally in Erfurt between the two emperors themselves, and much was agreed upon which neither the one nor the other intended to observe. A written treaty of alliance was besides concluded by Romanzov and Champagny, which was calculated with a view to a new war with Austria. The substance of the agreement consists in a closer alliance of the two powers against England, and the cession of Moldavia and Wallachia to Russia. Hitherto Napoleon had only been willing to concede this last point on conditions which referred to Silesia. In the fifth article of the Treaty of Erfurt, which was kept strictly secret, the two emperors agreed to conclude a peace with England on condition only that that country should acknowledge Moldavia and Wallachia as a part of the Russian Empire. Then follow several articles on the cession of those Turkish provinces. In the eleventh article it is stated, that further negotiations were to be carried on respecting a further partition. It

was agreed, too, that the treaty was to be kept secret for ten years. Buturlin boasts, with reason, that the emperor Alexander in Erfurt, by his Greco-Slavonian arts of deception, gained a victory over the Italo-Gallic talents of Napoleon; and, in fact, the very highest triumph is to outwit the deceiver.

Even as early as this Napoleon is said to have thrown out the idea of a marriage with Catherine Pavlovna, Alexander’s sister, which inferred, of course, a previous separation from the empress Josephine. Alexander, on his part, is said to have raised difficulties on the question of religion, and to have referred the matter to his mother, who very speedily had the princess betrothed to Duke Peter of Oldenburg. Moreover, the reception of the duke of Oldenburg into the confederation of the Rhine was one of the results of the meeting in Erfurt.

The war which broke out in April, 1809, between France and Austria, put the sincerity of the Russo-French alliance to a practical test. Russia complied with the letter of her engagements to the one belligerent power by declaring war against the other; but Prince Galitzin, who was to have made a powerful diversion in Galicia, came so late into the field and his movements were so dilatory that it was evident he had no desire to contribute to the success of his sovereign’s ally. There was no longer any show of cordiality in the diplomatic intercourse between France and Russia; but both parties found it convenient for the present to dissemble their mutual alienation. By the Treaty of Schönbrunn, signed by vanquished Austria (October 14th, 1809), that power ceded, partly to France and partly to the confederation of the Rhine, several towns in Germany and Italy, with their dependencies; she was despoiled, in favour of the duchy of Warsaw, of all western Galicia and the city of Cracow; and surrendered to Russia a territory whose population was estimated at 400,000 souls. The emperor of Austria, moreover, recognised the rights which Napoleon arrogated over the monarchies of the south of Europe, adhered to his continental system, and renounced all the countries comprised under the name of the Illyrian Provinces. But the house of Habsburg, true to the

[1809-1810 ]

adage, Tu, felix Austria, nube, retrieved its fortunes at the expense of its pride, by bestowing a daughter in marriage on the conqueror.

RENEWED WAR WITH TURKEY (1810 A.D.)

Immediately after Alexander’s return from Erfurt orders were given to open negotiations with the Turks. The conference took place at Jassy; but it was immediately broken off after the Russian plenipotentiaries had demanded, as preliminary conditions, the cession of Moldavia and Wallachia, and the expulsion of the British minister from Constantinople. Hostilities were then resumed. The Russians were commanded by Prince Prosorovski, and after his death by Prince Bagration. With the exception of Giurgevo, all the fortresses attacked by them fell into their hands, until they encountered the army of the grand vizir, near Silistria, and being defeated with a loss of ten thousand men (September 26th), were compelled to evacuate Bulgaria. The grand vizir, without taking advantage of his victory, retired to winter quarters.

In May, 1810, the Russian main army, under Kamenskoi, again crossed the Danube at Hirsova, passed through the Dobrudja, and marched straight against the Turkish main army to Shumla and Varna. At the same time, the corps of Generals Langeron and Sacken proceeded to blockade Silistria and Rustchuk. The Turks could nowhere keep the field. At Kavarna they were routed; at the storming of Bazardjik they lost ten thousand men; at the storming of Rasgrad three thousand. Silistria was reduced in seven days by Langeron. So far everything was favourable for the Russians. If they had added to their advantages the conquest of Rustchuk, the passes of Tirnova and of Sophia towards Adrianople would have been open, the fortress of Shumla would have been avoided, and the main army of the enemy would have been manœuvred out of it. The taking of Rustchuk, and above all the sparing of the troops, was consequently the next problem for General Kamenskoi. Instead of doing this, the Russians attempted to storm almost simultaneously the fortifications of Varna, Shumla, and Rustchuk, were repulsed from these three places, the defence of which was conducted by English officers, and

suffered so enormously, that the Turks felt themselves strong enough to come out from behind their intrenchments, and attack the Russian camp before Shumla. They failed, however, in their attempt to storm it.

To relieve Rustchuk, the grand vizir sent Mukhtar Pasha with picked troops, by way of Tirnova, to the Danube. But if the Turks with their united forces were too weak to force the Russians to abandon the intrenchments before Shumla, they could certainly not expect with a part of their army to rout the enemy near Rustchuk, where he stood with his united forces between their separate wings. Only in case Mukhtar Pasha, who had increased his forces to forty thousand men, entered Wallachia at Turna, and marched against Giurgevo, could the offensive have a meaning, or any influence, upon the siege of Rustchuk, because here it met with the weak point of the enemy. But to enter upon the offensive with an army in Wallachia, whilst the Russians stood before the fortresses of the Danube in Bulgaria, never came into the heads of the Turks. Mukhtar Pasha intrenched himself at the mouth of the Yantra to cover the passes of Tirnova and Sophia. On the 7th of September he was attacked in front, flank, and rear, held out with his best troops till the next morning, and then surrendered with five thousand men, and all his artillery. After this Sistovo and Cladova capitulated, and on the 27th of September Rustchuk and Giurgevo surrendered.

[1810-1811 ]

The road to Adrianople was now open for the Russians, but their enormous losses, caused by their own folly, would have prevented their assuming the offensive beyond the Balkan for this year, even if the season had not been so far advanced. Reinforcements for the next year could not be expected, as Napoleon was preparing to attack Russia, and therefore they began to negotiate. Another insurrection of the janissaries interrupted these negotiations, but did not induce the grand vizir to profit by this opportunity, and fall with his whole force upon the Russians, who, at this time, were scattered over the country from Widdin to Sophia and thence as far as Varna. Not until Czerni George, in February, 1811, had placed the principality of Servia under the protection of Russia, did the grand

vizir awake from his apathy in Thrace, and cross the Balkan, with only fifteen thousand men. He, however, proceeded so slowly that Kamenskoi had time enough to assemble sufficient forces.

They met at Lofteh on the Osma; the Turks were defeated, and lost three thousand men. Achmed Pasha, however, a violent and sturdy soldier, without any higher military education, led fifty thousand fresh troops to Shumla, and insisted upon their taking the offensive. The Russians had received no reinforcements, but Kutusov had taken the command. Without any considerable losses, he concentrated his small army at Silistria and Rustchuk, and abandoned Bulgaria as far as the latter place, after having rased the fortresses. In the battle before Rustchuk, on the 4th of July, the Turks were driven back, but on the 7th, they forced the twenty thousand Russians who stood on the right bank of the Danube to give up Rustchuk also, though not until its works had been rased.

Instead of crossing the river from the Dobrudja, and operating with a superior force upon the Russian lines of communication, the grand vizir allowed himself to be induced, by the retreat of Kutusov, to cross the Danube at Rustchuk, without a fortress in his rear Arrived on the left bank with his main army, a Russian flotilla barred his retreat, while Russian corps recrossed the Danube above and below Rustchuk, and took possession of the town (no longer fortified) and of the Turkish camp (September 7th). The grand vizir fled, but his main army, still consisting of 25,000 men and 56 pieces of artillery, was forced to surrender in the vicinity of Giurgevo. A few days afterwards Count St. Priest took Shirtov, with the whole of the Turkish flotilla on the Danube. Nicopoli and Widdin next surrendered, so that by the end of the campaign the Russians were masters of the whole right bank of the Danube. The Servians, also, aided by a body of Russians, had wrested from the Turks the last fortresses they held in the principality.

The grand vizir asked for a suspension of arms, with a view to negotiating a peace; but the terms now demanded by the victorious Russians were such as the Porte would not accede to. The war was continued in 1811, but always to the disadvantage of the Turks. Resolved on a last desperate effort, they assembled a formidable

army whilst the conference at Bucharest was still pending. At last, the rupture between France and Russia changed the aspect of affairs, and compelled the latter power to abandon the long-coveted prey when it was already in its grasp. The Russian minister, Italinski, contented himself with requiring that the Pruth should for the future form the boundary between the two empires. The sultan regarded even this concession as disgraceful; but the Russians carried their point by bribery, and the Treaty of Bucharest was concluded. Its chief provisions were these:

Article 4. The Pruth, from the point where it enters Moldavia to its confluence with the Danube, and thence the left bank of the latter to its embouchure on the Black Sea at Kilia, shall be the boundary between the two empires. Thus the Porte surrendered to Russia a third of Moldavia, with the fortresses of Khoczim and Bender, and all Bessarabia, with Ismail and Kilia. By the same article, the navigation of the Danube is common to the subjects of Russia and Turkey. The islands enclosed between the several arms of the river below Ismail are to remain waste. The rest of Moldavia and Wallachia are to be restored to the Turks in their actual condition. Article 6. The Asiatic frontier remains the same as it was before the war. Article 8 relates to the Servians, to whom the Porte grants an amnesty and some privileges, the interpretation of which offers a wide field for the exercise of diplomatic subtlety. Article 13. Russia accepts the mediation of the Porte for the conclusion of a peace with Persia, where hostilities had begun anew, at the instigation of the English ambassador

WAR WITH NAPOLEON

Notwithstanding all the demonstrations to the contrary made since the Peace of Tilsit, England, Russia, Prussia, and also Austria partially, always continued to maintain a certain mutual understanding, which was, however, kept very secret, and somewhat resembled a conspiracy. The most distinguished statesmen both in Russia and Prussia felt how unnatural was an alliance between Napoleon, Alexander, and Frederick William III, and directed

attention to the subject. This was also done on the part of England, and it is certain that the emperor Alexander, as early as the meeting in Erfurt in 1808, expressed his doubts respecting the duration of his alliance with France. The conduct of Russia in the campaign against Austria, in 1809, first shook Napoleon’s confidence in his ally. Mutual complaints and recriminations ensued; but neither party thought it advisable to give any prominence to their disunion, and Napoleon, even when he had entered, through Thugut, upon the subject of an Austrian marriage, still continued to carry on negotiations for an alliance with a Russian princess.

The enlargement of the territory of the duchy of Warsaw, extorted by Napoleon at the Peace of Schönbrunn, at length led to an exchange of diplomatic notes, which tended strongly to a war. The Poles naturally expected from Napoleon and his advisers that he would in some way give new life and currency to the name of Poland; against this the emperor of Russia earnestly protested. The whole of the diplomatic correspondence between Russia and France in the years 1810 and 1811 turns upon the use of the words Poles and Polish, although Russia had again obtained by the Peace of Schönbrunn a portion of Austrian Poland, as it had previously obtained a part of Prussian Poland by the Peace of Tilsit. Seeing that the whole of western Galicia, Zamoisk, and Cracow had been united to the duchy of Warsaw by the Peace of Schönbrunn, Russia called upon the emperor of the French to bind himself expressly by treaty not to revive the names of Pole and kingdom of Poland.

Before the end of 1809 many notes were exchanged concerning this point, apparently so insignificant, but in reality so important for the peace and safety of the Russian Empire. Napoleon agreed to give the assurance so earnestly desired by Alexander, and Caulaincourt, the French ambassador in St. Petersburg, signed a regular concession of the Russian demand in January, 1810. By the first two articles of this agreement it was laid down that the word Poland, or Polish, was not to be used when any reference was made to the enlargement of the duchy of Warsaw. By the third article the two emperors bound themselves not to revive or renew any of the old Polish orders. In the fifth, the emperor of the French agreed not

further to enlarge the duchy of Warsaw by the addition of provinces or cities belonging to the former state of Poland.

This agreement, signed by Caulaincourt, still required the confirmation of the emperor of the French: and Napoleon had given instructions to his ambassador only to agree to such an arrangement on condition that the agreement was drawn up in the usual diplomatic manner: that is to say, in employing words and phrases so chosen as to be capable of any subsequent interpretation which may best suit the parties. This was not done. The articles were very brief, the language so clear and definite as to be incapable of mistake or misrepresentation. Without directly refusing his sanction to the treaty, Napoleon required that it should be couched in different language, and caused a new draft of it to be presented in St. Petersburg. The Russians saw at once through his purpose, and Alexander expressed his displeasure in terms which plainly indicated to the French ambassador his belief that Napoleon was really meditating some hostile measures against him, and was only seeking to gain time by the treaty.

This occurred in February, 1810; in the following months both Romanzov and Caulaincourt took the greatest possible pains to bring the question to a favourable issue, and negotiations continued to be carried on respecting this subject till September. They could not agree; and after September there was no more talk of the treaty, much less of its alteration. The relation between the two emperors had undergone a complete change in the course of the year.

The cupidity of Russia, far from being glutted by the possession of Finland, great part of Prussian and Austrian Poland, Moldavia, and Bessarabia, still craved for more. Napoleon was, however, little inclined to concede Constantinople and the Mediterranean to his Russian ally (to whose empire he assigned the Danube as a boundary), or to put it in possession of the duchy of Warsaw. The Austrian marriage, which was effected in 1809, naturally led Russia to conclude that she would no longer be permitted to aggrandise herself at the expense of Austria, and Alexander, seeing that nothing more was to be gained by complaisance to France, consequently assumed a threatening posture, and condescended to listen to the

complaints of his agricultural and mercantile subjects. No Russian vessel durst venture out to sea, and a Russian fleet had been seized by the British in the harbours of Lisbon. At Riga lay immense stores of grain in want of a foreign market. On the 31st of December, 1810, Alexander published a fresh tariff permitting the importation of colonial products under a neutral flag (several hundred English ships arrived under the American flag), and prohibiting the importation of French manufactured goods. Not many weeks previously, on the 13th of December, Napoleon had annexed Oldenberg to France. The duke, Peter, was nearly related to the emperor of Russia, and Napoleon, notwithstanding his declared readiness to grant a compensation, refused to allow it to consist of the grand-duchy of Warsaw, and proposed a duchy of Erfurt, as yet uncreated, which Russia scornfully rejected.

The alliance between Russia, Sweden, and England was now speedily concluded. Sweden, which had vainly demanded from Napoleon the possession of Norway and a large supply of money, assumed a tone of indignation, threw open her harbours to the British merchantmen, and so openly carried on a contraband trade in Pomerania, that Napoleon, in order to maintain the continental system, was constrained to garrison Swedish Pomerania and Rügen and to disarm the Swedish inhabitants. Bernadotte, upon this, ranged himself entirely on the side of his opponents, without, however, coming to an open rupture, for which he awaited a declaration on the part of Russia The expressions made use of by Napoleon on the birth of the king of Rome at length filled up the measure of provocation. Intoxicated with success, he boasted, in an address to the mercantile classes, that he would, in despite of Russia, maintain the continental system, for he was lord over the whole of continental Europe; and that if Alexander had not concluded a treaty with him at Tilsit, he would have compelled him to do so at St. Petersburg. The pride of the haughty Russian was deeply wounded, and a rupture was nigh at hand.

[1811-1812 ..]

Russia had, meanwhile, anticipated Napoleon in making preparations for war. As early as 1811, a great Russian army stood

ready for the invasion of Poland, and might, as there were at that time but few French troops in Germany, easily have advanced as far as the Elbe. It remained, however, in a state of inactivity. Napoleon instantly prepared for war and fortified Dantzic. His continual proposals of peace, ever unsatisfactory to the ambition of the czar, remaining at length unanswered, he declared war.k

But, to get within reach of Russia, it was necessary for Napoleon to pass beyond Austria, to cross Prussia, and to conciliate Sweden and Turkey; an offensive alliance with these four powers was therefore indispensable. Austria was subject to the ascendency of Napoleon, and Prussia to his arms: to them, therefore, he had only to declare his intentions; Austria voluntarily and eagerly entered into his plans, and Prussia he easily prevailed on to join him.

Austria, however, did not act blindly. Situated between the two giant powers of the north and the west, she was not displeased to see them at war: she looked to their mutually weakening each other, and to the increase of her own strength by their exhaustion. On the 14th of March, 1812, she promised France thirty thousand men, but she prepared prudent secret instructions for them. She obtained a vague promise of an increase of territory as an indemnity for her share of the expenses of the war, and the possession of Galicia was guaranteed to her. She admitted, however, the future possibility of a cession of part of that province to the kingdom of Poland, but in exchange for that she would have received the Illyrian Provinces. The sixth article of the secret treaty establishes this fact.

The success of the war, therefore, in no degree depended on the cession of Galicia, or the difficulties arising from the Austrian jealousy respecting that possession. Napoleon consequently might, on his entrance into Vilna, have publicly proclaimed the liberation of the whole of Poland, instead of betraying the expectations of her people, confounding and rendering them indifferent by expressions of doubtful import. This was one of those decisive issues which occur in politics as well as in war, and which determine the future. No consideration ought to have made Napoleon swerve from his purpose. But whether it was that he reckoned too much on the ascendency of his genius, or the strength of his army and the

weakness of Alexander; or that, considering what he left behind him, he felt it too dangerous to carry on so distant a war slowly and methodically; or whether, as we shall presently be told by himself, he had doubts of the success of his undertaking, certain it is that he either neglected or could not yet venture to proclaim the liberation of that country whose freedom he had come to restore. Yet he had sent an ambassador to her diet; and when this inconsistency was remarked to him he replied that that nomination was an act of war, which only bound him during the war, while by his words he would be bound both in war and peace. Thus it was that he made no other answer to the enthusiasm of the Lithuanians than evasive expressions, at the very time he was following up his attack on Alexander to the very capital of his empire.

He even neglected to clear the southern Polish provinces of the feeble hostile armies which kept the patriotism of their inhabitants in check, and to secure, by strongly organising their insurrection, a solid basis of operation. Accustomed to short methods and to rapid attacks, he wished to do as he had done before, in spite of the difference of places and circumstances; for such is the weakness of man that he is always led by imitation, either of others or of himself, which in the latter case is habit, for habit is nothing more than the imitation of one’s self. Accordingly, it is by their strongest side that great men are often undone!h

Napoleon Invades Russia (1812 A.D.)

On the 24th of June, 1812, Napoleon crossed the Niemen, the Russian frontier, not far from Kovno. The season was already too far advanced. It may be that, deceived by the mildness of the winter of 1806 to 1807, he imagined it possible to protract the campaign without peril to himself until the winter months. No enemy appeared to oppose his progress. Barclay de Tolly, the Russian commander-inchief, pursued the system followed by the Scythians against Dairus, and perpetually retiring before the enemy gradually drew him deep into the dreary and deserted steppes. This plan originated with

[1812 ..]

Scharnhorst, by whom General Lieven was advised not to hazard an engagement until the winter, and to turn a deaf ear to every proposal of peace. General Lieven, on reaching Barclay’s headquarters, took into his confidence Colonel Toll, a German, Barclay’s right hand, and Lieutenant-Colonel Clausewitz, also a German, afterwards noted for his strategical works.

General Pfül, another German, at that time high in the emperor’s confidence, and almost all the Russian generals opposed Scharnhorst’s plan, and continued to advance with a view of giving battle: but on Napoleon’s appearance at the head of an army greatly their superior in number, before the Russians had been able to concentrate their forces, they were naturally compelled to retire before him; and, on the prevention, for some weeks, of the junction of a newly levied Russian army under Prince Bagration with the forces under Barclay, owing to the rapidity of Napoleon’s advance, Scharnhorst’s plan was adopted as the only one feasible.

Whilst the French were advancing, a warm and tedious discussion was carried on so long in the imperial Russian council of war at Vilna, whether to defend that city, or adopt the plan of Barclay de Tolly, the minister of war and commander-in-chief, that they were at length obliged to march precipitately to the Dvina with the sacrifice of considerable stores, and to take possession of a fortified camp which had been established at Drissa. As late as the 27th the emperor Alexander and the whole of his splendid staff and court were assembled at a ball, at the castle of Zacrest, near Vilna, belonging to General Bennigsen, so that the French found everything on the 28th just as it had been prepared for the reception of the emperor of Russia. They plundered the castle, and carried off the furniture as booty; the Russians were even obliged to leave behind them considerable quantities of ammunition and provisions.

In this way the line of the Russian defences was broken through; and even a portion of their army under Platov and Bagration would have been cut off, had the king of Westphalia obeyed the commands of his brother with the necessary rapidity. The difficulties of carrying on war in such an inhospitable country as Lithuania and Russia became apparent even at Vilna; the carriages and wagons fell

behind, the cannon were obliged to be left, discipline became relaxed, above ten thousand horses had already fallen, and their carcases poisoned the air. General Balakov could scarcely be considered serious in the proposals which he then made for peace in the name of the emperor of Russia, because the Russians required as a preliminary to all negotiation that the French army should first retire behind the Niemen. The mission of a general, who had been minister of police, and had therefore had great experience in obtaining information, had no doubt a very different object in view from that of making peace at such a moment.

Napoleon, in the hope of overtaking the Russians, and of compelling them to give battle, pushed onwards by forced marches; the supplies were unable to follow, and numbers of the men and horses sank from exhaustion, owing to over-fatigue, heat, and hunger. On the arrival of Napoleon in Witepsk, of Schwarzenberg in Volhinia, of the Prussians before Riga, the army might have halted, reconquered Poland, have been organised, the men put into winter quarters, the army have again taken the field early in the spring, and the conquest of Russia have been slowly but surely completed. But Napoleon had resolved upon terminating the war in one rapid campaign, upon defeating the Russians, seizing their metropolis, and dictating terms of peace. He incessantly pursued his retreating opponent, whose footsteps were marked by the flames of the cities and villages and by the devastated country to their rear. The first serious opposition was made at Smolensk, whence the Russians, however, speedily retreated after setting the city on fire. On the same day, the Bavarians, who had diverged to one side during their advance, had a furious encounter at Polotsk with a body of Russian troops under Wittgenstein. The Bavarians remained stationary in this part of the country for the purpose of watching the movements of that general, whilst Napoleon, careless of the peril with which he was threatened by the approach of winter and by the multitude of enemies gathered to his rear, advanced with the main body of the grand army from Smolensk across the wasted country upon Moscow, the ancient metropolis of the Russian empire.

Russia, at that time engaged in a war with Turkey, whose frontiers were watched by an immense army under Kutusov, used her utmost efforts, in which she was aided by England, to conciliate the Porte in order to turn the whole of her forces against Napoleon. By a masterstroke of political intrigue, the Porte was made to conclude a disadvantageous peace at Bucharest on the 28th of May, as we have already related. A Russian army under Tchitchakov was now enabled to drive the Austrians out of Volhinia, whilst a considerable force under Kutusov joined Barclay. Buturlin, the Russian historian of the war, states that the national troops opposed to the invaders numbered 217,000 in the first line, and 35,000 in the second. Chambray, whose details are very minute, after deducting the men in hospital, gives the number of those present under arms as 235,000 of the regular army, without reckoning the garrisons of Riga, etc. This computation exceeds that of Buturlin, under the same circumstances, by 17,000. M. de Fezensac allows 230,000 for the total of the two armies of Barclay de Tolly and Bagration, but adds the army of Tormassov on their extreme left, 68,000, and that defending Courland, on the extreme right, 34,000, to make up the Russian total of 330,000 men.

Had the Russians at this time hazarded an engagement, their defeat was certain. Moscow could not have been saved. Barclay consequently resolved not to come to an engagement, but to husband his forces and to attack the French during the winter. The intended surrender of Moscow without a blow was, nevertheless, deeply resented as a national disgrace; the army and the people raised a clamour. Kutuzov, though immeasurably inferior to Barclay, was nominated commander-in-chief, took up a position on the little river Moskva near Borodino, about two days’ journey from Moscow. A bloody engagement took place there on the 7th of September, in which Napoleon, in order to spare his guards, neglected to follow up his advantage with his usual energy, and allowed the defeated Russians, whom he might have totally annihilated, to escape. Napoleon triumphed; but at what a price!—after a fearful struggle, in which he lost forty thousand men in killed and wounded, the latter of whom perished, almost to a man, owing to want and neglect.k

The Abandonment of Moscow

On his birthday, which was the 30th of August (11th of September of the Russian calendar), the emperor Alexander received a report from Prince Kontonzov of the battle that had taken place at Borodino on the 26th of August, and which as the commander-in-chief wrote, “had terminated by the enemy not gaining a single step of territory in spite of their superior forces.” To this Kutuzov added that after having spent the night on the field of battle, he had, in view of the enormous losses sustained by the army, retreated to Mozhaisk. The losses on either side amounted to forty thousand men. As Ermolov very justly expressed it, “the French army was dashed to pieces against the Russian.” Although the emperor Alexander was not led into any error as to the real signification of the battle of Borodino, yet wishing to maintain the hopes of the nation as to the successful termination of the struggle with Napoleon and their confidence in Kutuzov, he accepted the report of the conflict of the 26th of August as the announcement of a victory. Prince Kutuzov was created general field-marshal and granted a sum of 100,000 rubles. Barclay de Tolly was rewarded with the order of St. George of the second class, and the mortally wounded Prince Bagration with a sum of 50,000 rubles. Fourteen generals received the order of St. George of the third class, and all the privates who had taken part in the battle were given five rubles each.

Prince Kutuzov’s despatch of the 27th of August to the emperor Alexander was read by Prince Gortchakov at the Nevski monastery before a thanksgiving service which took place in the presence of their majesties, and was printed in the Northern Post. But the following lines were omitted from the report: “Your imperial majesty will deign to agree that after a most sanguinary battle, which lasted fifteen hours, our army and that of the enemy could not fail to be in disorder. Moreover, through the losses sustained this day the position has naturally become incompatible with the depleted number of our troops—therefore, all our aims being directed to the destruction of the French army, I have come to the decision to fall back six versts, that is, beyond Mozhaisk.”

A moment of anxious expectation approached in St. Petersburg. Meanwhile Kutuzov, retreating step by step, led the army to Moscow, and on the 1st of September he assembled a council of war at the village of Filiakh. There was decided the fate of the first capital of the empire. After prolonged debates Kutuzov concluded the conference by saying: “I know that I shall have to pay the damage, but I sacrifice myself for the good of my country. I give the order to retreat.”

It was already towards nightfall when Rostoptchin received the following letter from Kutuzov: “The fact that the enemy has divided his columns upon Zvenigorod and Borovsk, together with the disadvantageous position now occupied by our troops, oblige me to my sorrow to abandon Moscow. The army is marching on the route to Riazan.” It was thus that Rostoptchin received the first definite information of Kutuzov’s intention to leave Moscow a few hours before the French were in sight of the capital; under these circumstances the Moscow commander-in-chief did all that was possible on his side and took all measures for setting the town on fire at the approach of the army. Rostoptchin departed unhindered in a droshky by the back gates.

When on the 2nd of September Napoleon reached the Dragomilovski barriers, he expected to find there a deputation, begging that the city might be spared; but instead of that he received the news that Moscow had been abandoned by its inhabitants. “Moscow deserted! What an improbable event! We must make sure of it. Go and bring the boyars to me,” said he to Count Darn, whom he sent into the town. Instead of the boyars a few foreigners were collected who confirmed the news that Moscow had been abandoned by nearly all its inhabitants. Having passed the night on the outskirts of the city, on the morning of the 3rd of September Napoleon transferred his headquarters to the Kremlin. But here a still more unexpected occurrence awaited him. The fires, which had already commenced the eve, had not ceased burning; and on the night between the 3rd and the 4th of September the flames, driven along by a strong wind, had enveloped the greater part of the town. At midday the flames reached the Kremlin, and Napoleon was forced to seek a refuge in the Petrovski palace, where he remained until the

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.