t

n

o

r

F

,

1

:

t

e

e

h

S

k

c

a

B

,

1

:

t

e

e

h

S

Th is chapter describes the installation process for Windows, OS X, and Linux systems. For the latter, you’re going to ensure that you have the correct dependencies and compile it from the source.INSTALLING NODE.JS IS a painless process. Since its conception, one of its goals has been maintaining a small number of dependencies that would make the compilation or installation of the project very seamless.THE SETUP1CHAPTER06_9781119962595-ch01.indd   706_9781119962595-ch01.indd   78/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

2

:

t

e

e

h

S

8PART I • Getting Started: Setup and ConceptsNote: When you see lines prefi xed with $ in the code snippets in the book, you should type these expressions into your OS shell.INSTALLING ON WINDOWSOn Windows, go to http://nodejs.org and download the MSI installer. Every release of node has a corresponding MSI installer that you need to download and execute.Th e fi lename follows the format node-v?.?.?.msi. Upon executing it, simply follow the instructions in the setup wizard shown in Figure 1-1.To ensure that the installation worked, open the shell or command prompt by running cmd.exe and typing $ node –version.Th e version name of the package you just installed should display.INSTALLING ON OS XOn the Mac, similarly to Windows, you can leverage an installer package. From the Node.JS website, download the PKG fi le that follows the format node-v?.?.?.pkg. If you want to compile it instead, ensure you have XCode installed and follow the Compilation instructions for Linux.Run the downloaded package and follow the simple steps (see Figure 1-2).To ensure installation was successful, open the shell or terminal by running Terminal.app (you can type in “Terminal” in Spotlight to locate it) and type in $ node –version.Th e version of Node you just installed should be outputted.INSTALLING ON LINUXCompiling Node.JS is almost just as easy as installing binaries. To compile it in most *nix systems, simply make sure a C/C++ compiler and the OpenSSL libraries are available.Figure 1-1: The Node.JS setup wizard.Figure 1-2: The Node.JS package installer.06_9781119962595-ch01.indd   806_9781119962595-ch01.indd   88/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

2

:

t

e

e

h

S

CHAPTER 1 • The Setup9Most Linux distributions come with a package manager that allows for the easy installation of these.For example, for Amazon Linux, you use> sudo yum install gcc gcc-c++ openssl-devel curlOn Ubuntu, the installation is slightly diff erent; you use> sudo apt-get install g++ libssl-dev apache2-utils curlCOMPILINGFrom your OS terminal, execute the following commands:Note: Replace ? with the latest available version of node in the following example.$ curl -O http://nodejs.org/dist/node-v?.?.?.tar.gz$ tar -xzvf node-v?.?.?.tar.gz$ cd node-v?.?.?$ ./configure$ make$ make test$ make installIf the make test command aborts with errors, I recommend you stop the installation and post a log of the ./configure, make, and make test commands to the Node.JS mailing list.ENSURING THAT IT WORKSLaunch a terminal or equivalent, such as XTerm, and type in $ node –version.Th e version of Node you just installed should be outputted.THE NODE REPLTo run the Node REPL, simply type node.Try running some JavaScript expressions. For example:> Object.keys(global)Note: When you see lines prefi xed with > in the code snippets in the book, you should run these expressions in the REPL.06_9781119962595-ch01.indd   906_9781119962595-ch01.indd   98/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

3

:

t

e

e

h

S

10PART I • Getting Started: Setup and ConceptsTh e REPL is one of my favorite tools for quickly verifying that diff erent Node or vanilla JavaScript APIs work as expected. While developing larger modules, it’s oft en useful to check a certain API works exactly the way you remember it when unsure. To that end, opening a separate terminal tab and quickly evaluating some JavaScript primitives in a REPL helps immensely.EXECUTING A FILELike most scripted programming languages, Node can interpret the contents of a fi le by appending a path to the node command.With your favorite text editor, create a fi le called my-web-server.js, with the following contents:var http = require(‘http’);var serv = http.createServer(function (req, res) {  res.writeHead(200, { ’Content-Type’: ’text/html’ });  res.end(’<marquee>Smashing Node!</marquee>’);});serv.listen(3000);Run the fi le:$ node my-web-server.jsTh en, as shown in Figure 1-3, point your web browser to http://localhost:3000.In this code snippet, you’re leveraging the power of Node to script a fully compliant HTTP server that serves a basic HTML document. Th is is the traditional example used whenever Node.JS is being discussed, because it demonstrates the power of creating a web server just like Apache or IIS with only a few lines of JavaScript.NPMTh e Node Package Manager (NPM) allows you to easily manage modules in projects by downloading packages, resolving dependencies, running tests, and installing command-line utilities.Even though doing so is not essential to the core functionality of the project, you truly need to work effi  ciently on projects that rely on other pre-existing modules released by third parties.Figure 1-3: Serving a basic HTML document in Node.06_9781119962595-ch01.indd   1006_9781119962595-ch01.indd   108/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

3

:

t

e

e

h

S

CHAPTER 1 • The Setup11NPM is a program written in Node.JS and shipped with the binary packages (the MSI Windows installer, and the PKG for the Mac). If you compiled node from the source fi les, you want to install NPM as follows:$ curl http://npmjs.org/install.sh | shTo ensure successful installation, issue the following command:$ npm --versionTh e NPM version should be displayed.INSTALLING MODULESTo illustrate the installation of a module with NPM, install the colors library in the direc-tory my-project and then create an index.js fi le:$ mkdir my-project/$ cd my-project/$ npm install colorsVerify that the project was installed by ensuring the path node_modules/colors was created.Th en edit index.js with your favorite editor:$ vim index.jsAnd add the following contents:require(‘colors’);console.log(‘smashing node’.rainbow);Th e result should look like Figure 1-4.Figure 1-4: The result of installing a module06_9781119962595-ch01.indd   1106_9781119962595-ch01.indd   118/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

4

:

t

e

e

h

S

12PART I • Getting Started: Setup and ConceptsDEFINING YOUR OWN MODULETo defi ne your own module, you need to create a package.json fi le. Defi ning your own module has three fundamental benefi ts:◾ Allows you to easily share the dependencies of your application with others, without sending along the node_modules directory. Because npm install takes care of fetching everything, distributing this directory wouldn’t make sense. Th is is especially important in SCM systems like Git.◾ Allows you to easily track the versions of the modules you depend on that you know work. For example, when you wrote a particular project, you ran npm install colors and that installed colors 0.5.0. A year later, due to API changes, perhaps the latest colors are no longer compatible with your project, and if you were to run npm install without specifying the version, your project would break.◾ Makes redistribution possible. Did your project turn out fi ne and you want to share it with others? Because you have a package.json, the command npm publish. publishes it to the NPM registry for everyone to install.In the directory created earlier (my-project), remove the node_modules directory and create a package.json fi le:$ rm -r node_modules$ vim package.jsonTh en add the following contents:{    “name”: “my-colors-project”  , “version”: “0.0.1”  , “dependencies”: {      “colors”: “0.5.0”    }}Note: Th e contents of this fi le must be valid JSON. Valid JavaScript is not enough. Th is means that you must make sure, for example, to use double quotes for all strings, including property names.Th e package.json fi le is the fi le that describes your project to both Node.JS and NPM. Th e only required fi elds are name and version. Normally, modules have dependencies, which is an object that references other projects by the name and version they defi ned in their package.json fi les.Save the fi le, install the local project, and run index.js again:06_9781119962595-ch01.indd   1206_9781119962595-ch01.indd   128/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

4

:

t

e

e

h

S

CHAPTER 1 • The Setup13$ npm install$ node index   # notice that you don’t need to include “.js”!In this case, the intention is to create a module for internal use. If you wanted, NPM makes it really easy to publish a module by running:$ npm publishTo tell Node which fi le to look for when someone calls require(‘my-colors-project’) we can specify the main property in the package.json:{    “name”: “my-colors-project”  , “version”: “0.0.1”  , “main”: “./index”  , “dependencies”: {      “colors”: “0.5.0”    }}When you learn how to make modules export APIs, the main property will become a lot more important, because you will need it to defi ne the entry point of your modules (which sometimes are comprised of multiple fi les). To learn about all the possible properties for the package.json fi le, run:$ npm help jsonTip: If you never intend to publish a certain project, add “private”: “true” to your package.json. Th is prevents accidental publication.INSTALLING BINARY UTILITIESSome projects distribute command-line tools that were written in Node. When that’s the case, you need to install them with the -g fl ag.For example, the web framework you’re going to learn in this book called express contains an executable utility to create projects.$ npm install -g expressTh en try it out by creating a directory and running “express” inside:$ mkdir my-site$ cd mysite$ express06_9781119962595-ch01.indd   1306_9781119962595-ch01.indd   138/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

5

:

t

e

e

h

S

14PART I • Getting Started: Setup and ConceptsTip: If you want to distribute a script like this, include a fl ag “bin”: “./path/to/script” pointing to your executable script or binary when publishing.EXPLORING THE NPM REGISTRYOnce you get comfortable with the Node.JS module system in Chapter 4, you should be able to write programs that leverage any module in the ecosystem.NPM has a rich registry that contains thousands of modules. Two commands are instrumen-tal in your exploration of the registry: search and view.If you want to search for plugins related to realtime, for example, you would execute the following:$ npm search realtimeTh is will search all the published modules that contain MySQL in their name, tags, and description fi elds.Once you fi nd a package that interests you, you can see its package.json and other properties related to the NPM registry by running npm view followed by the module name. For example:$ npm view socket.ioTip: If you want to learn more about a certain NPM command, type “npm help <command>.” For example, “npm help publish” will teach you more about how to publish modules.SUMMARYAft er this chapter, you should now have a working Node.JS + NPM environment.In addition to being able to run the node and npm commands, you should now have a basic understanding of how to execute simple scripts, but also how to put together modules with dependencies.You now know that an important keyword in Node.JS is require, which allows for module and API interoperability, and which will be an important subject in Chapter 4, aft er quickly reviewing the language basics.You also are now aware of the NPM registry, which is the gateway to the Node.JS module ecosystem. Node.JS is an open source project, and as a result many of the programs that are written with it are also open source and available for you to reuse, a few keystrokes away.06_9781119962595-ch01.indd   1406_9781119962595-ch01.indd   148/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

5

:

t

e

e

h

S

In addition, most of the code you’ll write is in compliance with the “good parts” of JavaScript that Douglas Crockford enounced in his famous book, JavaScript: Th e Good Parts.Th is chapter is divided into two parts:◾ Basic JavaScript. Th e fundamentals of the language. Th ey apply everywhere: node, browser, and standards committee.◾ v8 JavaScript. Some features used in v8 are not available in all browsers, especially Internet Explorer, because they’ve recently been standardized. Others are nonstandard, but you still use them because they solve fundamental problems.In addition, the next chapter covers the language extensions and features exclusively available in Node.INTRODUCTIONJAVASCRIPT IS A prototype-based, object-oriented, loosely-typed dynamic scripting language. It has powerful features from the functional world, such as closures and higher-order functions, that are of special interest here.JavaScript is technically an implementation of the ECMAScript language standard. It’s important to know that with Node, because of v8, you’ll be primarily dealing with an implementation that gets close to the standard, with the exception of a few extra features. Th is means that the JavaScript you’re going to be dealing with has some impor-tant diff erences with the one that earned the language its bad reputation in the browser world.JAVASCRIPT: AN OVERVIEW2CHAPTER07_9781119962595-ch02.indd   1507_9781119962595-ch02.indd   158/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

6

:

t

e

e

h

S

16PART I • Getting Started: Setup and ConceptsBASIC JAVASCRIPTTh is chapter assumes that you’re somewhat familiar with JavaScript and its syntax. It goes over some fundamental concepts you must understand if you want to work with Node.js.TYPESYou can divide JavaScript types into two groups: primitive and complex. When one of the primitive types is accessed, you work directly on its value. When a complex type is accessed, you work on a reference to the value.◾ Th e primitive types are number, boolean, string, null, and undefined.◾ Th e complex types are array, function, and object.To illustrate:// primitivesvar a = 5;var b = a;b = 6;a; // will be 5b; // will be 6// complexvar a = [‘hello’, ‘world’];var b = a;b[0] = ‘bye’;a[0]; // will be ’bye’b[0]; // will be ‘bye’In the second example, b contains the same reference to the value as a does. Hence, when you access the fi rst member of the array, you alter the original, so a[0] === b[0].TYPE HICCUPSCorrectly identifying the type of value a certain variable holds remains a challenge in JavaScript.Because JavaScript has constructors for most primitives like in other languages with object-oriented features, you can create a string in these two ways:var a = ‘woot’;var b = new String(‘woot’);a + b; // ‘woot woot’07_9781119962595-ch02.indd   1607_9781119962595-ch02.indd   168/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

6

:

t

e

e

h

S

CHAPTER 2 • JavaScript: An Overview17If you use the typeof and instanceof operators on these two variables, however, things get interesting:typeof a; // ‘string’typeof b; // ‘object’a instanceof String; // falseb instanceof String; // trueHowever, both are defi nitely strings that have the same prototypical methods:a.substr == b.substr; // trueAnd they evaluate in the same way with the == operator but not with ===:a == b; // truea === b; // falseConsidering these discrepancies, I encourage you to always defi ne your types in the literal way, avoiding new.It’s important to remember that certain values will be evaluate to false in conditional expressions: null, undefined, ‘’, 0:var a = 0;if (a) {  // this will never execute}a == false; // truea === false; // falseAlso noteworthy is the fact that typeof doesn’t recognize null as its own type:typeof null == ‘object’; // true, unfortunatelyAnd the same goes for arrays, even if defi ned with [], as shown here:typeof [] == ‘object’; // trueYou can be thankful that v8 provides a way of identifying an array without resorting to hacks. In browsers, you typically inspect the internal [[Class]] value of an object: Object.prototype.toString.call([]) == ‘[object Array]’. Th is is an immutable property of objects that has the benefi t of working across diff erent contexts (for example, browser frames), whereas instanceof Array is true only for arrays initialized within that particular context.07_9781119962595-ch02.indd   1707_9781119962595-ch02.indd   178/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

7

:

t

e

e

h

S

18PART I • Getting Started: Setup and ConceptsFUNCTIONSFunctions are of utmost importance in JavaScript.Th ey’re fi rst class: they can be stored in variables as references, and then you can pass them around as if they were any other object:var a = function () {}console.log(a); // passing the function as a parameterAll functions in JavaScript can be named. It’s important to distinguish between the function name and the variable name:var a = function a () {  ‘function’ == typeof a; // true};THIS, FUNCTION#CALL, AND FUNCTION#APPLYWhen the following function is called, the value of this is the global object. In the browser, that’s window:function a () {  window == this; // true;};a();By using the .call and .apply methods, you can change the reference of this to a diff erent object when calling the function:function a () {  this.a == ‘b’; // true}a.call({ a: ‘b’ });Th e diff erence between call and apply is that call takes a list of parameters to pass to the function following, whereas apply takes an array:function a (b, c) {  b == ‘first’; // true  c == ‘second’; // true}a.call({ a: ‘b’ }, ‘first’, ‘second’)a.apply({ a: ‘b’ }, [‘first’, ‘second’]);07_9781119962595-ch02.indd   1807_9781119962595-ch02.indd   188/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

7

:

t

e

e

h

S

CHAPTER 2 • JavaScript: An Overview19FUNCTION ARITYAn interesting property of a function is its arity, which refers to the number of arguments that the function was declared with. In JavaScript, this equates to the length property of a function:var a = function (a, b, c);a.length == 3; // trueEven though less common in the browser, this feature is important to us because it’s leveraged by some popular Node.JS frameworks to off er diff erent functionality depending on the number of parameters the functions you pass around take.CLOSURESIn JavaScript, every time a function is called, a new scope is defi ned.Variables defi ned within a scope are accessible only to that scope and inner scopes (that is, scopes defi ned within that scope):var a = 5;function woot () {  a == 5; // true  var a = 6;  function test () {    a == 6; // true  }  test();};woot();Self-invoked functions are a mechanism by which you declare and call an anonymous function where your only goal is defi ning a new scope:var a = 3;(function () {  var a = 5;})();a == 3 // true;Th ese functions are very useful when you want to declare private variables that shouldn’t be exposed to another piece of code.07_9781119962595-ch02.indd   1907_9781119962595-ch02.indd   198/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

8

:

t

e

e

h

S

20PART I • Getting Started: Setup and ConceptsCLASSESIn JavaScript, there’s no class keyword. A class is defi ned like a function instead:function Animal () { }To defi ne a method on all the instances of Animal that you create, you set it on the prototype:Animal.prototype.eat = function (food) {  // eat method}It’s worth mentioning that within functions in the prototype, this doesn’t refer to the global object like regular functions, but to the class instance instead:function Animal (name) {  this.name = name;}Animal.prototype.getName () {  return this.name;};var animal = new Animal(‘tobi’);a.getName() == ‘tobi’; // trueINHERITANCEJavaScript has prototypical inheritance. Traditionally, you simulate classical inheritance as follows.You defi ne another constructor that’s going to inherit from Animal:function Ferret () { };To defi ne the inheritance chain, you initialize an Animal object and assign it to the Ferret.prototype.// you inheritFerret.prototype = new Animal();You can then defi ne methods and properties exclusive to your subclass:// you specialize the type property for all ferretsFerret.prototype.type = ‘domestic’;07_9781119962595-ch02.indd   2007_9781119962595-ch02.indd   208/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

8

:

t

e

e

h

S

CHAPTER 2 • JavaScript: An Overview21To override methods and call the parent, you reference the prototype:Ferret.prototype.eat = function (food) {  Animal.prototype.eat.call(this, food);  // ferret-specific logic here}Th is technique is almost perfect. It’s the best performing across the board (compared to the alternative functional technique) and doesn’t break the instanceof operator:var animal = new Animal();animal instanceof Animal // trueanimal instanceof Ferret // falsevar ferret = new Ferret();ferret instanceof Animal // trueferret instanceof Ferret // trueIts major drawback is that an object is initialized when the inheritance is declared (Ferret.prototype = new Animal), which might be undesirable. A way around this problem is to include a conditional statement in the constructor:function Animal (a) {  if (false !== a) return;  // do constructor stuff}Ferret.prototype = new Animal(false)Another workaround is to defi ne a new, empty constructor and override its prototype:function Animal () {  // constructor stuff}function f () {};f.prototype = Animal.prototype;Ferret.prototype = new f;Fortunately, v8 has a cleaner solution for this, which is described later in this chapter.TRY {} CATCH {}try/catch allows you to capture an exception. Th e following code throws one:> var a = 5;> a()TypeError: Property ‘a’ of object #<Object> is not a function07_9781119962595-ch02.indd   2107_9781119962595-ch02.indd   218/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

9

:

t

e

e

h

S

22PART I • Getting Started: Setup and ConceptsWhen a function throws an error, execution stops:function () {  throw new Error(‘hi’);  console.log(‘hi’); // this will never execute}If you use try/catch, you can handle the error and execution continues:function () {  var a = 5;  try {    a();  } catch (e) {    e instanceof Error; // true  }  console.log(‘you got here!’);}V8 JAVASCRIPTSo far you’ve looked at the JavaScript features that are most relevant to dealing with the language in most environments, including ancient browsers.With the introduction of the Chrome web browser came a new JavaScript engine, v8, which has been quickly pushing the boundaries by providing us with an extremely fast execution environment that stays up-to-date and supports the latest ECMAScript features.Some of these features address defi ciencies in the language. Others were introduced thanks to the advent of client-side frameworks like jQuery and PrototypeJS, because they provided extensions or utilities that are so frequently used it’s now unimaginable to consider the JavaScript language without them.In this section you’ll learn about the most useful features that you can take advantage of from v8 to write more concise and faster code that fi ts right it with the style of code that the most popular Node.JS frameworks and libraries adopt.OBJECT#KEYSIf you wanted to obtain the keys for the following object (a and c)var a = { a: ‘b’, c: ‘d’ };Th en normally iterate as follows: for (var i in a) { }07_9781119962595-ch02.indd   2207_9781119962595-ch02.indd   228/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

9

:

t

e

e

h

S

CHAPTER 2 • JavaScript: An Overview23By iterating over the keys, you can collect them in an array. However, if you were to extend the Object.prototype as follows:Object.prototype.c = ‘d’;To avoid getting c in the list of keys you would need to run a hasOwnProperty check:for (var i in a) {  if (a.hasOwnProperty(i)) {}}To get around that complication, to get all the own keys in an object, in v8 you can safely usevar a = { a: ‘b’, c: ‘d’ };Object.keys(a); // [‘a’, ‘c’]ARRAY#ISARRAYLike you saw before, the typeof operator will return “object” for arrays. Most of the time, however, you want to check that an array is actually an array. Array.isArray returns true for arrays and false for any other value:Array.isArray(new Array) // trueArray.isArray([]) // trueArray.isArray(null) // falseArray.isArray(arguments) // falseARRAY METHODSTo loop over an array, you can use forEach (similar to jQuery $.each):// will print 1 2 and 3[1, 2, 3].forEach(function (v) {  console.log(v);});To fi lter elements out of an array, you can use filter (similar to jQuery $.grep)[1, 2, 3].forEach(function (v) {  return v < 3;}); // will return [1, 2]To change the value of each item, you can use map (similar to jQuery $.map)[5, 10, 15].map(function (v) {  return v * 2;}); // will return [10, 20, 30]07_9781119962595-ch02.indd   2307_9781119962595-ch02.indd   238/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

0

1

:

t

e

e

h

S

24PART I • Getting Started: Setup and ConceptsAlso available but less commonly used are the methods reduce, reduceRight, and lastIndexOf.STRING METHODSTo remove space in the beginning and ending of a string, use‘  hello  ‘.trim(); // ‘hello’JSONv8 exposes JSON.stringify and JSON.parse to decode and encode JSON, respectively.JSON is an encoding specifi cation that closely resembles the JavaScript object literal, utilized by many web services and APIs:var obj = JSON.parse(‘{“a”:”b”}’)obj.a == ‘b’; // trueFUNCTION#BIND.bind (equivalent to jQuery’s $.proxy) allows you to change the reference of this:function a () {  this.hello == ‘world’; // true};var b = a.bind({ hello: ‘world’ });b();FUNCTION#NAMEIn v8, the nonstandard property name of a function is supported:var a = function woot () {};a.name == ‘woot’; // trueTh is property is used internally by v8 in stack traces. When an error is thrown, v8 shows a stack trace, which is the succession of function calls it made to reach the point where the error occurred:> var woot = function () { throw new Error(); };> woot()Error    at [object Context]:1:3207_9781119962595-ch02.indd   2407_9781119962595-ch02.indd   248/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

0

1

:

t

e

e

h

S

CHAPTER 2 • JavaScript: An Overview25In this case, v8 is not able to assign a name to the function reference. If you name it, however, v8 will be able to include it in the stack traces as shown here:> var woot = function buggy () { throw new Error(); };> woot()Error    at buggy ([object Context]:1:34)Because naming signifi cantly aids in debugging, I always recommend you name your functions._PROTO_ (INHERITANCE)__proto__ makes it easy for you to defi ne the inheritance chain:function Animal () { }function Ferret () { }Ferret.prototype.__proto__ = Animal.prototype;Th is is a very useful feature that removes the need to:◾ Resort to intermediate constructors, as shown in the previous section.◾ Leverage OOP toolkits or utilities. You don’t need to require any third-party modules to expressively declare prototypical inheritance.ACCESSORSYou are able to defi ne properties that call functions when they’re accessed (__defineGetter__) or set (__defineSetter__).As an example, defi ne a property called ago that returns the time ago in words for a Date object. Many times, especially in the soft ware you create, you want to express time in words relative to a certain point. For example, it’s easier for people to understand that something happened three seconds ago than reading the complete date.Th e following example adds an ago getter to all the Date instances that will output the distance of time in words to the present. Simply accessing the property will execute the function you defi ne, without having to explicitly call it.// Based on prettyDate by John Resig (MIT license)Date.prototype.__defineGetter__(‘ago’, function () {  var diff = (((new Date()).getTime() - this.getTime()) / 1000)    , day_diff = Math.floor(diff / 86400);07_9781119962595-ch02.indd   2507_9781119962595-ch02.indd   258/1/12   10:55 AM8/1/12   10:55 AMt

n

o

r

F

,

1

1

:

t

e

e

h

S

26PART I • Getting Started: Setup and Concepts  return day_diff == 0 && (      diff < 60 && “just now” ||      diff < 120 && “1 minute ago” ||      diff < 3600 && Math.floor( diff / 60 ) + “ minutes ago” ||      diff < 7200 && “1 hour ago” ||      diff < 86400 && Math.floor( diff / 3600 ) + “ hours ago”) ||      day_diff == 1 && “Yesterday” ||      day_diff < 7 && day_diff + “ days ago” ||      Math.ceil( day_diff / 7 ) + “ weeks ago”;});Th en you simply refer to the ago property. Notice that you’re not executing a function, yet it’s still being executed transparently for you:var a = new Date(‘12/12/1990’); // my birth datea.ago // 1071 weeks agoSUMMARYUnderstanding this chapter is essential to getting up to speed with the quirks of the language and handicaps of most environments the language has traditionally been run in, such as old browsers. Due to JavaScript evolving really slowly and being somewhat overlooked for years, many developers have invested signifi cant amounts of time in developing techniques to write the most effi  cient and maintainable code, and have characterized what aspects of the language don’t work as expected.v8 has done a fantastic job at keeping up to date with the recent editions of ECMA, and continues to do so. Th e Node.JS core team of developers always ensures that when you install the latest version of Node, you always get the most recent version of v8. Th is opens up a new panorama for server-side development, since we can leverage APIs that are easier to under-stand and faster to execute.Hopefully during this chapter you’ve learned some of the features that Node developers commonly use, which are those that are defi ning the present and future of JavaScript.07_9781119962595-ch02.indd   2607_9781119962595-ch02.indd   268/1/12   10:55 AM8/1/12   10:55 AMk

c

a

B

,

1

1

:

t

e

e

h

S

CONTENTSPART I: GETTING STARTED: SETUP AND CONCEPTS 5Chapter 1: Th e Setup 7Installing on Windows 8Installing on OS X 8Installing on Linux 8Compiling 9Ensuring that it works 9Th e Node REPL 9Executing a fi le 10NPM 10Installing modules 11Defi ning your own module 12Installing binary utilities 13Exploring the NPM registry 14Summary 14Chapter 2: JavaScript: An Overview 15Introduction 15Basic JavaScript 16Types 16Type hiccups 16Functions 18this, Function#call, and Function#apply 18Function arity 19Closures 19Classes 20Inheritance 20try {} catch {} 21v8 JavaScript 22Object#keys 22Array#isArray 23Array methods 23String methods 24JSON 24Function#bind 2402_9781119962595-ftoc.indd   iv02_9781119962595-ftoc.indd   iv8/1/12   10:45 AM8/1/12   10:45 AMt

n

o

r

F

,

2

1

:

t

e

e

h

S

VCONTENTSFunction#name 24_proto_ (inheritance) 25Accessors 25Summary 26Chapter 3: Blocking and Non-blocking IO 27With great power comes great responsibility 28Blocking-ness 29A single-threaded world 31Error handling 33Stack traces 35Summary 37Chapter 4: Node JavaScript 39Th e global object 40Useful globals 40Th e module system 41Absolute and relative modules 41Exposing APIs 44Events 45Buff ers 47Summary 48PART II: ESSENTIAL NODE APIS 49Chapter 5: CLI and FS APIs: Your First Application 51Requirements 52Writing your fi rst program 52Creating the module 53Sync or async? 54Understanding streams 55Input and ouput 57Refactoring 59Interacting with the fs 61Exploring the CLI 63Argv 63Working directory 64Environmental variables 65Exiting 65Signals 65ANSI escape codes 66Exploring the fs module 66Streams 67Watch 67Summary 6802_9781119962595-ftoc.indd   v02_9781119962595-ftoc.indd   v8/1/12   10:45 AM8/1/12   10:45 AMk

c

a

B

,

2

1

:

t

e

e

h

S

VICONTENTSChapter 6: TCP 69What are the characteristics of TCP? 70Connection-oriented communication and same-order delivery 70Byte orientation 70Reliability 71Flow control 71Congestion control 71Telnet 71A TCP chat program 74Creating the module 74Understanding the net.server API 74Receiving connections 76Th e data event 77State and keeping track of connections 79Wrap up 81An IRC Client program 83Creating the module 83Understanding the net#Stream API 84Implementing part of the IRC protocol 84Testing with a real-world IRC server 85Summary 85Chapter 7: HTTP 87Th e structure of HTTP 88Headers 89Connections 93A simple web server 94Creating the module 95Printing out the form 95Methods and URLs 97Data 99Putting the pieces together 102Bullet-proofi ng 103A Twitter web client 104Creating the module 104Making a simple HTTP request 104Sending a body of data 106Getting tweets 107A superagent to the rescue 110Reloading HTTP servers with up 111Summary 11202_9781119962595-ftoc.indd   vi02_9781119962595-ftoc.indd   vi8/1/12   10:45 AM8/1/12   10:45 AMt

n

o

r

F

,

3

1

:

t

e

e

h

S

CONTENTSVIIPART III: WEB DEVELOPMENT 113Chapter 8: Connect 115A simple website with HTTP 116A simple website with Connect 119Middleware 121Writing reusable middleware 122Static middleware 127Query 128Logger 129Body parser 131Cookies 134Session 134REDIS sessions 140methodOverride 141basicAuth 141Summary 144Chapter 9: Express 145A simple express app 146Creating the module 146HTML 146Setup 147Defi ning routes 148Search 150Run 152Settings 153Template engines 154Error handling 155Convenience methods 155Routes 157Middleware 159Organization strategies 160Summary 162Chapter 10: WebSocket 163AJAX 164HTML5 WebSocket 166An Echo Example 167Setting it up 167Setting up the server 168Setting up the client 169Running the server 170Mouse cursors 171Setting up the example 171Setting up the server 17202_9781119962595-ftoc.indd   vii02_9781119962595-ftoc.indd   vii8/1/12   10:45 AM8/1/12   10:45 AMk

c

a

B

,

3

1

:

t

e

e

h

S

VIIICONTENTSSetting up the client 174Running the server 176Th e Challenges Ahead 177Close doesn’t mean disconnect 177JSON 177Reconnections 177Broadcasting 177WebSockets are HTML5: Older browsers don’t support them 177Th e solution 178Summary 178Chapter 11: Socket.IO 179Transports 180Disconnected versus closed 180Events 180Namespaces 181A chat program 182Setting up the program 182Setting up the server 182Setting up the client 183Events and Broadcasting 185Ensuring reception 190A DJ-by-turns application 191Extending the chat 191Integrating with the Grooveshark API 193Playing 196Summary 201PART IV: DATABASES 203Chapter 12: MongoDB 205Installation 207Accessing MongoDB: A user authentication example 208Setting up the application 208Creating the Express app 208Connecting to MongoDB 212Creating documents 214Finding documents 215Authentication middleware 217Validation 218Atomicity 219Safe mode 219Introducing Mongoose 220Defi ning a model 220Defi ning nested keys 222Defi ning embedded documents 22202_9781119962595-ftoc.indd   viii02_9781119962595-ftoc.indd   viii8/1/12   10:45 AM8/1/12   10:45 AMt

n

o

r

F

,

4

1

:

t

e

e

h

S

CONTENTSIXSetting up indexes 222Middleware 223Inspecting the state of the model 223Querying 224Extending queries 224Sorting 224Making Selections 224Limiting 225Skipping 225Populating keys automatically 225Casting 225A mongoose example 226Setting up the application 226Refactoring 226Setting up models 227Summary 229Chapter 13: MySQL 231node-mysql 232Setting it up 232Th e Express app 232Connecting to MySQL 234Initializing the script 234Creating data 238Fetching data 242sequelize 244Setting up sequelize 245Setting up the Express app 245Connecting sequelize 248Defi ning models and synchronizing 249Creating data 250Retrieving data 253Removing data 254Wrapping up 256Summary 257Chapter 14: Redis 259Installing Redis 261Th e Redis query language 261Data types 262Strings 263Hashes 263Lists 265Sets 265Sorted sets 266Redis and Node 266Implementing a social graph with node-redis 267Summary 27602_9781119962595-ftoc.indd   ix02_9781119962595-ftoc.indd   ix8/1/12   10:45 AM8/1/12   10:45 AMk

c

a

B

,

4

1

:

t

e

e

h

S

XCONTENTSPART V: TESTING 277Chapter 15: Code Sharing 279What can be shared? 280Writing compatible JavaScript 280Exposing modules 280Shimming ECMA APIs 282Shimming Node APIs 283Shimming browser APIs 284Cross-browser inheritance 284Putting it all together: browserbuild 285A basic example 286Summary 288Chapter 16: Testing 289Simple testing 290Th e test subject 290Th e test strategy 290Th e test program 291Expect.JS 292API overview 292Mocha 294Testing asynchronous code 295BDD style 297TDD style 298Exports style 298Taking Mocha to the browser 299Summary 30002_9781119962595-ftoc.indd   x02_9781119962595-ftoc.indd   x8/1/12   10:45 AM8/1/12   10:45 AM