21
INDEX COPYRIGHTED MATERIAL

INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

INDEX

bindex.indd 351bindex.indd 351 21/09/12 4:03 PM21/09/12 4:03 PM

COPYRIG

HTED M

ATERIAL

Page 2: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

bindex.indd 352bindex.indd 352 21/09/12 4:03 PM21/09/12 4:03 PM

Page 3: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

353

INDEX

Symbols

[ ] operator, buffers and, 30= operator

Jade encoding and, 231string appearance and, 231

A

absolute fi le paths, 55.addListener() function, binding

callbacks and, 38–39age, validating (Mongoose), 327–328AnyEvent (Perl), 17app.js fi le (Express.js)

app.js fi le Express creates (listing), 219–220

middleware and, 220, 229routes and, 223

applicationschat applications, extending, 250–253debugging. See debugging modules and

applicationstesting. See testing modules and

applicationsweb applications. See Express.js for web

applications.apply() method, 41array.forEach, iterating and, 189array.map() function, 190array.reduce function, 191, 192arrays, logging with console.log

function, 168articles schemas (Mongoose)

Article list partial template (listing), 348Article schema (listing), 341–342Detail view and (listings), 345–347Loading (listing), 345

assertion testing modulesassert module, 159–161, 162assertion functions in node-tap,

161–163async dependency, Mongoose and, 320–321async module

cascading, 186–187detecting, 193–194executing in parallel, 185–186executing in series, 184–185fi ltering, 192–193installing, 183iterating, 189–190mapping, 190–191queuing, 187–189reducing, 191–192Simple squaring server (listing),

183–184async.forEach

Iterating over a collection using (listing), 189–190

ordering of results and, 188asynchronous dependencies, 320asynchronous middleware, 200–201asynchronous modules, testing, 163–166asynchronous programming

basics of, 16–17JavaScript and, 17–19ordering of results and, 188

async.parallel, 320–321

bindex.indd 353bindex.indd 353 21/09/12 4:03 PM21/09/12 4:03 PM

Page 4: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

354

attributes – chats

attributes, virtual (Mongoose), 332–338automated tests, writing. See testing modules

and applicationsavatars, CouchDB documents and, 298–301,

304–309

B

binary buffer implementation. See buffersbinding callbacks, 38–39birthdays, validating age and (Mongoose),

327–328boomerang effect

avoiding, 179–183basics, 177–179

bufferedstream module, 302, 303buffers

bytes in, 30–31copying, 32creating, 30decoding, 32–33in Node, 29–30reading from fi les and, 59slicing, 32UDP and, 133

building Node from source code, 7buttons, for executed instructions

(debugging), 175bytes, buffers and, 29, 30–31

C

caching modules, 27–28call stack, debugging and, 175callback fl ow, controlling

async module. See async moduleboomerang effect, avoiding, 179–183boomerang effect basics, 177–179

callback soup. See boomerang effectcallbacks

binding callbacks using .addListener() or .on() functions, 38–39

executing using .once() function, 40–41external commands and, 64–65

http.request() call, 115reading database data and, 272registering inside middleware, 201–203retrieving database information

and, 272standard callback patterns, 36

cancelling execution of functions, 46–47cascading

cascade function, 183executing functions and, 186–187

Certifi cate Authority (CA), 143, 151certifi cates

Certifi cate Signing Request (CSR) fi les, 140

HTTPS servers and, 150public keys, 140validating (HTTPS), 151–152, 153–154verifying (TLS), 143–144, 147–148

changing headers (HTTP servers), 99chat applications, extending, 250–253chat servers. See also TCP chat servers,

buildingdetecting disconnections, 254–255Socket.IO chat server that allows users to

join rooms (listing), 257–259Socket.IO chat servers, 246–247,

251–252TLS chat servers, creating, 145–146

chats, building with Socket.IOapplication structure, 246basics of, 245–246chat application, extending, 250–253chat clients, 247–249chat servers, 246disconnections, detecting, 254–255namespaces and, 259Redis, 260–263server-side application, distributing,

259–263Simple Socket.IO chat client (listing),

249–250Simple Socket.IO chat server

(listing), 247users, separating into rooms, 255–259

chats, HTTP and, 241–242

bindex.indd 354bindex.indd 354 21/09/12 4:03 PM21/09/12 4:03 PM

Page 5: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

355

child processes – concurrency

child processesbasics of, 69creating, 69exit notifi cation, 72–73listening for data from, 69–70need for using, 63sending data to, 70–72

child_process modulebasics of, 69importing, 64

child.kill method, 74Chrome inspector (Google), debugging

and, 173chunked encoding

HTTP chunked responses and timers, 102

HTTP servers and, 99–100clearTimeout function, for canceling

function execution, 46–47CLI (command-line interface), running Node

as, 8client connections (TCP)

accepting, 89–90closing, 105–106, 109–111collecting, 90–91listening for, 88reading data from, 90removing closed, 92–93

clients. See also command-line clientsbuilding (UDP), 134chat clients, Socket.IO and, 247–250client connections, accepting (TCP),

89–90client connections, listening for (TCP), 88collecting (TCP), 90–91CouchDB clients, HTTP and, 281creating (HTTPS), 152–154data and (TLS), 142initializing (HTTPS), 152slow client problem, 80–82Socket.IO basic client, 244Socket.IO chat client that accepts /j

<room> command (listing), 255–257Socket.IO chat client that supports user

login (listing), 252–253

Socket.IO-based chat client that formats messages (listing), 292–294

Socket.IO-based chat client that presents avatars (listing), 298–301

Socket.IO-based server that creates CouchDB client when initializing (listing), 282–284

TCP. See TCP clients, building; TCP command-line clients, building (example)

TLS clients, building, 143–145closing

connections (TCP), 105–106, 109–111connections (TLS), 142, 144–145fi les, 60–61servers (TCP), 88sockets (UDP), 134TCP servers, 88

closuresasynchronous programming and, 19JavaScript and, 18–19

code. See also source codemodules and, 23

code listings. See listingscollections

databases, 313detecting value of, 193–194fi ltering, 192–193iterating over, 189–190mapping, 190–191MongoDB, 312squaring and, 191–192

command line, reading from (UDP), 135command-line clients

building (TCP). See TCP command-line clients, building (example)

creating (TLS), 146–147creating (UDP), 135–136

command-line interface (CLI), running Node as, 8

commands, external, executing, 64–68

CommonJS module system, 24CommonJS modules standard, 23concurrency, controlling, 187, 188

bindex.indd 355bindex.indd 355 21/09/12 4:03 PM21/09/12 4:03 PM

Page 6: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

356

Connect HTTP middleware framework – data

Connect HTTP middleware framework. See also HTTP middleware

basics of, 198, 206Connect HTTP server, 199Connect middleware that writes headers

(listing), 200Connect server that uses HelloWorld

middleware (listing), 199Connect server that uses ReplyText

middleware (listing), 199cookies, parsing, 212–213errors, handling, 208–209Express.js and, 217, 221logging requests, 206–208middleware bundled in, installing, 198query strings, parsing, 210–211ReplyText middleware (listing), 199request body, parsing, 211–212sessions, using, 213–216simple component, 198–199static fi les, serving, 209–210

connecting. See also CouchDB, connecting to with Nano; Mongoose, connecting to Mongo DB with

to MySQL databases, 268–269reconnecting to servers (TCP), 108–109to TCP servers, 104, 107to TLS servers, 143

connections. See also client connections (TCP)

closing (TLS), 142, 144–145connection pools, 276listening for (HTTPS), 150–151listening for (TLS servers), 141–142multiple to MySQL, 276WebSockets, 244

conn.end() method, 105–106, 110console.log function, 167–169continuation-passing style (CPS), 36controlling external processes. See external

processescookies

basics of, 212–213parsing (Connect), 212–213request module and (HTTP), 127

copying buffers, 32core modules, 25–26CouchDB, connecting to with Nano

CouchDB basics, 277–278databases, connecting to, 281dependency and, 278documents, storing, 285fi les, attaching to documents. See

CouchDB documents, attaching fi les toNano, 278Socket.IO-based server that creates

CouchDB client when initializing (listing), 282–284

views. See CouchDB viewsCouchDB documents, attaching fi les to

Socket.IO-based chat client that presents avatars (listing), 298–301

Socket.IO-based chat server that presents avatars (listing), 305–309

CouchDB viewsbasics of, 286–287New version of Socket.IO-based chat

client that formats messages (listing), 292–294

New version of Socket.IO-based chat server that sends structured message documents (listing), 294–297

Socket.IO-based server that creates database and view you need (listing), 288–290

CPS (continuation-passing style), 36cryptography basics, 139–140CSR (Certifi cate Signing Request) fi les, 140curl utility, 7, 201, 202, 205, 212

D

Dahl, Ryan, 3, 17–18data

broadcasting (TCP chat servers), 91–92listening for from child processes, 69–70reading effi ciently from databases,

272–276reading from connections (TCP chat

servers), 90

bindex.indd 356bindex.indd 356 21/09/12 4:03 PM21/09/12 4:03 PM

Page 7: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

357

databases – event callbacks

receiving from servers (UDP), 136securely adding to databases, 270–272sending and receiving (TCP), 105sending to child processes, 70–72sending to servers (UDP), 135streams and, 76–77TLS and, 142, 144writing into streams, 78

databases. See also document-oriented databases; relational databases

persistent, for storing user data, 238datagrams. See also UDP (User Datagram

Protocol)defi ned, 129

datescomparing, 161date fi elds, adding (Mongoose), 328tracking (Mongoose), 338–339

--debug option, 173--debug-brk option, 173debugging modules and applications

with console.log, 167–169with debugger, 169–173with Node Inspector, 173–175

Declaring named functions (listing), 179–181decoding buffers, 32–33deep equality, 160–161deferring execution of functions, 46, 47–48delays/no delays (TCP servers), 87–88dependencies

async dependency, Mongoose and, 320–321

installing (Express.js), 219Nano and, 278New version of package.json manifest

containing request dependency (listing), 329

NPM and, 8packages and, 11–13testing applications and, 158

design documents (CouchDB), 287, 288detecting

disconnections, chats and, 254–255using async.detect, 193–194

disconnections, detecting (chats), 254–255

document-oriented databases. See also MongoDB

basics of, 311vs. relational databases, 311

documentsin database collections, 313design documents, CouchDB and, 287fi les, attaching to CouchDB documents.

See CouchDB documents, attaching fi les to

referencing documents (Mongoose), 341–347

storing (CouchDB), 285downloading. See also websites for

downloadingNode source code, 6–7

draining of streams, 78

E

echo server, creating (UDP), 132–133email fi elds, validating (Mongoose), 324emitting events. See event emittersencoding

creating buffers and, 30request body (HTTP middleware), 211Sending form-encoded request body

(HTTP), 125–126Sending JSON-encoded request body

(HTTP), 126–127encryption. See public keysequality, assertions and, 160–161, 162error handling

Connect, 208–209inside middleware, 203–206TCP connections and, 106TCP servers, 88–89

errorsbuffer operations and, 31CouchDB, 282, 284MongoDB error codes, 322–323standard error stream, child processes

and, 70validation errors (Mongoose), 325

event callbacks, 16

bindex.indd 357bindex.indd 357 21/09/12 4:03 PM21/09/12 4:03 PM

Page 8: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

358

event emitters – folder modules, loading

event emittersbasics of, 35creating, 41–43defi ned, 35, 36, 37–38event emitter API, 38–41event emitter pattern basics, 36–37event types, 37–38standard callback patterns, 36

event listenersbinding multiple, 39–40.removeAllListeners() function and,

41.removeListener() function and, 38,

40, 41removing from event emitters, 40

event loopsbasics of, 16–17blocking, 48deferring function execution and, 47–48escaping, 49ticks, 47–48

Event Machine (Ruby’s), 17event-driven programming, Node and, 16–17EventEmitter object, console.log and,

168events

basics of, 16client events and HTML, 241client events and JavaScript, 241data events, receiving through closed

connections, 106emitting, 42–43. See also event emittersevent types, event emitters and, 37–38net.Server, (TCP servers) and, 84

exec function, in child_process module, 64

executable fi les, modules and, 11executing, callbacks using .once() function,

40–41exporting

functions, 25modules, 24–28

Express.js for web applicationsbasics of, 217initializing, 218–220

installing globally, 218middleware, setting up, 220–222routing requests. See routes, handling

(Express.js); routing requests (Express.js)

external processeschild processes, spawning. See child

processesexternal commands, executing, 64–68need for creation and control of, 63signaling and killing, 73–74

extracting fi le path components, 55–56

F

falsy values, 160fi elds (MongoDB)

defi ned, 312email fi elds, validating (Mongoose), 324gender fi elds, 326–327modifi ers and, 330unique username fi elds, 322

fi le modules, loading, 26fi le paths

defi ned, 54manipulating, 54–57

fi lesattaching to CouchDB documents. See

CouchDB documents, attaching fi les tobasics of dealing with, 53–54closing, 60–61fi les descriptors, 53–54fs module, 57–58opening, 58reading from, 59–61servers that serve static fi les, building,

101–102static fi les, serving (Connect), 209–210writing to, 60

fi le-system streams, 79–80fi ltering

collections, 192–193database storage and, 331–332

fl ushed streams, 78folder modules, loading, 26

bindex.indd 358bindex.indd 358 21/09/12 4:03 PM21/09/12 4:03 PM

Page 9: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

359

formats – HTTP (HyperText Transfer Protocol)

formatsNew version of Socket.IO-based chat

client that formats messages (listing), 292–294

when creating middleware components, 207–208

formatting, util.format function and, 168

formidable third-party module, 301, 303–304

fs modulebasics of, 57–58fs.close(fd[,callback]) function,

60 fs.createReadableStream() function, 79–80

fs.exists function, 56fs.open function, 58fs.read function, 59fs.readFile function, 141, 143fs.stat function, 57–58fs.write function, 60

functionsdeclaring to avoid boomerang effect,

179–183executing in series, callback fl ow and,

184–185exporting, 25in JavaScript, 18, 19

functions, scheduling with timersbasics of, 45–46cancelling execution of, 46–47deferring execution of, 46, 47–48event loops and, 47–49scheduling or canceling repetitive

execution, 47serialization, forcing, 49–50

G

Geisendörfer, Felix, 301gender fi elds (Mongoose), 326–327GET requests (HTTP), 113–114getters, using (Mongoose), 331–332global mode (NPM), 9–10

global namespaces, JavaScript and, 23Google Chrome inspector, debugging

and, 173

H

handler function, 302handshake protocol (WebSockets), 242–243headers

changing or setting (HTTP servers), 99Connect middleware that writes a header

(listing), 200http.serverresponse object, 98–99Including WriteHeader middleware in

HelloWorld app (listing), 200removing (HTTP servers), 99req.headers (http.ServerRequest

object), 97Sending custom headers (listing), 124showing user’s login (Express.js),

230–231writing (HTTP servers), 98

Hello WorldHello World! HTTP server, 95–96HelloWorld server includes SaveRequest

middleware, 201helper functions, async module, 183, 184history of Node, 3HTML (HypertText Markup Language)

client events and, 241HTML fi le with Node.js HTTP server,

serving (listing), 245platforms that support, 217serving though Node.js servers,

244–245HTTP (HyperText Transfer Protocol)

application frameworks, 198basics of, 95, 113, 197chats and, 241–242CouchDB clients and, 281HTML fi le with Node.js HTTP server,

serving (listing), 245limitations of, 241–242platforms that support, 217

bindex.indd 359bindex.indd 359 21/09/12 4:03 PM21/09/12 4:03 PM

Page 10: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

360

HTTP (continued) – Jade templating language

HTTP (continued)real-time web applications and,

241, 242HTTP middleware asynchronous, 200–201callbacks, registering inside,

201–203Connect basics, 198. See also Connect

HTTP middleware frameworkhandling errors inside, 203–206middleware basics, 197–198need for, 197–198other middleware, 216

HTTP requestsbasics of, 113CouchDB connections and, 281GET, 113–114HTTP basics, 95, 113, 197http.request function options,

114–115pooling sockets with http.Agent,

116–118response body, 116response object attributes, 115–116simplifying. See request module for

simplifying HTTP requestsHTTP servers

chunked encoding, 99–100chunked response and timers, 102creating, 95–96HTTP basics, 95, 113, 197http.ServerRequest object,

97–98http.ServerResponse object, 98–99securing with HTTPS, 149–152shutting down, 101simple static fi le servers, building,

101–102http.ClientRequest instance, 152http.request function, 37HTTPS

building secure HTTP servers with, 149–152

clients, creating, 152–154http.Server, TCP and, 83

I

_id fi elds (MongoDB), 344indexes, defi ning (Mongoose), 340–341inequality assertions, 160–161inheriting, from event emitter, 42init() function, debugging and, 171initialized buffers, creating, 31initializing

Express.js applications, 218–220HTTPS clients, 152TLS clients, 143TLS servers, 141

installation wizards, 4–5installing

async module, 183modules, 10–11Mongoose, 313Nano, 278node-mysql, 268node-tap, 158packages. See Node Package Manager

(NPM)Redis servers, 260request module (HTTP), 118–120Socket.IO, 243–245

installing Node, 3–13on Mac OS X, 5Node basics, 3–4Node history, 3using source code, 6–8on Windows, 4–5

instance methods, defi ning (Mongoose), 347–348

IrisCouch, 281iterating, asynchronously, 189–190iteration, async module and, 183

J

/j <room> command, Socket.IO chat client that accepts (listing), 255–257

Jade templating languageExpress.js and, 219HTML encoding and, 231

bindex.indd 360bindex.indd 360 21/09/12 4:03 PM21/09/12 4:03 PM

Page 11: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

361

JavaScript – listings

JavaScriptasynchronous programming and, 17–19client events and, 241CouchDB and, 277history of, 23Node and, 3–4, 18truthy values and, 160

join command, chat rooms and, 257joining fi le paths, 54.js extension, loading modules and, 26JSON

CouchDB and, 277Sending JSON-encoded request body,

126–127

K

keep-alive functionality (sockets), 87killing, external processes, 74killSignal option, 65, 66

L

librariesbasic for Node, 6connecting/communicating with MySQL

databases with, 268–269libssl-dev, installing Node and, 6listening

for connections (HTTPS), 150–151for connections (TLS servers), 141–142for data from child processes, 69–70

listings+1 app application, testing, 71–72+1 app example application, 70–71package.json manifest containing request

dependency, 329app.js fi le Express creates for you

(listing), 219–220Application package.json manifest

fi le., 313Application with bug, 169–170Application with custom error

handler, 205

Article detail view template in views/articles/article.jade, 345, 346

Article list partial template, 348Article list template in views/articles/

index.jade, 346–347Article model, 342Article route listeners, 342Article schema, 341–342async.detect, using, 193–194async.filter, using, 192–193Async.parallel example, 185–186async.queue, using, 187Async.series example, 184–185Boomerang effect, demonstration of,

178–179Cascading using async.waterfall, 186Changed layout fi le to include user info

on header, 231Child process parsing environment

variable, 68Client package.json manifest, 164Command-line TCP client that

reconnects when disconnected, 111–112

Command-line UDP client, 136Completed user route listeners, 225Connect body parser middleware,

211, 213Connect error handler, 208–209Connect middleware that writes a

header, 200Connect query string parser

middleware, 210Connect server that uses HelloWorld

middleware, 199Connect server that uses ReplyText

middleware, 199Connect session middleware, 214Connect static server middleware, 209Connecting and querying MySQL, 268Declaring named functions, 179–181Error handling middleware, 204Executing a command with augmented

environment variables, 67Executing an external command, 64

bindex.indd 361bindex.indd 361 21/09/12 4:03 PM21/09/12 4:03 PM

Page 12: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

362

listings (continued) – listings

listings (continued)Fake users, 224Generic fl ow control mechanism,

181–183Generic ReplyText middleware, 199Getting child process exit code, 73Getting child process exit signal, 73Hello World! HTTP server, 95–96HelloWorld server includes SaveRequest

middleware, 201HTML fi le with Node.js HTTP server,

serving, 245HTTP chunked response and timers

example, 102HTTP server that sums two integers, 163Including WriteHeader middleware in

HelloWorld app, 200Iterating over a collection using async.forEach, 189–190

Lifecycle example of a TCP server, 84–85

Listening for child exit event, 72Load User route middleware, 236Load user route middleware using user

model, 315Logger middleware, using, 206Login form, 232Making POST requests, 123–124Making requests that will be redirected

by servers, 122Making simple requests, 121Mapping a collection using async.map,

190–191Middleware component for loading an

article in routes/middleware//nlload_article.js, 345

Middleware component that throws errors, 203

Middleware that saves requests into fi les, 201

MySQL application, 274–275New middleware to restrict user to

session user, 238New user form template, 227–228Not_logged_in middleware, 234

Package.json manifest containing async dependency, 320

Parent process setting environment variable, 68

Piping a movie to HTTP response, 100Piping into sockets, 86Piping out sockets, 86Piping output of a process to HTTP

response, 100Reducing a collection asynchronously

using async.reduce, 191–192Request introspector HTTP server, 120Routes/index.js, 223Sending custom headers, 124Sending form-encoded request body,

125–126Sending JSON-encoded request body,

126–127Server with middleware that throws

error, 203–204Session routes, 229–230, 234–235Simple echo TCP server, 85Simple HelloWorld middleware, 198Simple HTTP static fi le server, 101–102Simple Socket.IO chat client, 249–250Simple Socket.IO chat server, 247Simple squaring server, 183–184Simple TCP chat server, 92–93Simple UDP server, 131Simplifi ed error-handling middleware

component, 206Socket.IO basic client, 244Socket.IO chat client that accepts /j

<room> command, 255–257Socket.IO chat client that supports user

login, 252–253Socket.IO chat server that allows users to

join a room, 257–259Socket.IO chat server that detects

disconnections, 254–255Socket.IO chat server that supports user

login, 251–252Socket.IO chat server that uses a Redis

store, 261–263Socket.IO client, 244

bindex.indd 362bindex.indd 362 21/09/12 4:03 PM21/09/12 4:03 PM

Page 13: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

363

Live Edit – memory

Socket.IO servers, setting up, 243Socket.IO-based chat client that formats

messages, 292–294Socket.IO-based chat client that presents

avatars, 298–301Socket.IO-based chat server that presents

avatars, 305–309Socket.IO-based chat server that sends

structured message documents, 294–297

Socket.IO-based server example you’ll build upon, 279–280

Socket.IO-based server that creates CouchDB client when initializing, 282–284

Socket.IO-based server that creates database and view you need, 288–290

Spawning a child process, 69Sum client module, 164Sum client tests, 165–166TCP chat server, 89–92TCP client that attempts to reconnect,

109TCP client that reconnects immediately,

108TLS chat client, 146–147TLS chat server, 145–146User creation form using full_name

virtual attribute in/nlviews/users/new.jade, 334–335

User creation form with birthday fi eld in views/users//nlnew.jade fi le, 328

User creation form with gender fi eld in views/users//nlnew.jade, 326–327

User list template, 226User list template using full_name virtual

attribute, 336User model in data/models/user.js, 315User Partial for Headers, 230–231User profi le template, 227User profi le template using full_name

virtual attribute/nlin views/users/profi le.jade, 335

User profi le template using twitter_url virtual attribute in/nlviews/users/profi le.jade, 332–333

User routes, 234–235, 237User routes now using user Mongoose

model, 316–317User schema in data/schemas/user.js., 314User schema with new enumerated

gender fi eld in data//nlschemas/user.js fi le, 326

User schema with new validated email fi eld in data/schemas//nluser.js, 324

User schema with unique index in data/schemas/user.js, 322

User signup form, 233Users list view, 224Users list with paging in views/users/

index.jade, 318, 319–320Users routes, 223

Live Edit, debugging and, 175load balancers, WebSockets and, 260loading modules, 24–28local mode (NPM), 9, 10logging requests (Connect), 206–208login

Express.js, 232Mongoose and, 323Socket.IO chat client that supports user

login (listing), 252–253Socket.IO chat server that supports user

login (listing), 251–252long polling, defi ned, 242Lua, blocking and non-blocking and, 17

M

Mac OS X, installing Node on, 5mapping

CouchDB and, 286synchronous iteration and, 190–191

maxElementsPerPage confi guration variable, 318

memorybuffers and, 30, 32loading fi les into, 36

bindex.indd 363bindex.indd 363 21/09/12 4:03 PM21/09/12 4:03 PM

Page 14: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

364

messages – net module

messageslistening for (UDP), 130–131message information (UDP), 132multicast (UDP), 137–138sending (UDP), 134sending back to senders (UDP), 132–133UDP and, 130waiting for (UDP), 132

methodsevent emitter API and, 38instance methods, defi ning (Mongoose),

347–348req.method (http.ServerRequest

object), 97static methods, defi ning (Mongoose),

348–349middleware. See also HTTP middleware

Load User route middleware (listing), 236

method override middleware, Express.js and, 221

Middleware component for loading an article in routes/middleware//nlload_article.js (listing), 345

route middleware, 234–238router middleware (Express.js), 221setting up (Express.js), 220–222types of, 216updating for Mongoose, 315

models (Mongoose)Article model (listing), 342basics of defi ning, 315database access and, 313–314

modifi ers, using (Mongoose), 330–331modules

assertion testing modules, 159–163asynchronous modules, testing,

163–166debugging. See debugging modules and

applicationsexporting, 24–28installing/uninstalling, 10–11loading with Node, 24, 25–28Mongoose module. See Mongoose,

connecting to Mongo DB with

testing. See testing modules and applications

MongoDB, 312. See also Mongoose, connecting to Mongo DB with

MongoHQ, 312Mongoose, connecting to Mongo DB with

async dependency and, 320–321basics (MongoDB), 312basics (Mongoose), 313default values, using, 338–339getters, using, 331–332indexes, defi ning, 340–341installing Mongoose, 313instance methods, defi ning, 347–348login and, 323making connections, 314models, database access and,

313–314models, defi ning, 315models, using in route listeners, 315modifi ers, using, 330–331paging and, 318–320referencing documents, 341–347route behavior, modifying,

315–318schemas, defi ning, 314static methods, defi ning, 348–349user creation route listener and,

321–322validators, using, 324–330virtual attributes, using, 332–338

multicast (UDP), 136–138multicasting, 137multi-threading, 15–16MySQL. See node-mysql

N

names in Mongoose, 333–338namespaces, building chats and, 259Nano, 278. See also CouchDB, connecting to

with Nanonet module

connecting to TCP servers with, 104TCP servers and, 83

bindex.indd 364bindex.indd 364 21/09/12 4:03 PM21/09/12 4:03 PM

Page 15: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

365

net.createConnection() function – pipe() function, slow client problem and

net.createConnection() function, 105net.Server

TCP servers and, 83, 84TLS and, 141

networking streams, 80Node

asynchronous programming and, 17–19basics of, 3–4closures and, 18–19event-driven programming and, 16–17history of, 3HTML fi le with Node.js HTTP server,

serving (listing), 245installing on Mac OS X, 5installing on Windows, 4–5installing using source code, 6–8JavaScript and, 17–19programming limitations and, 15–16

Node Inspector, 173–175Node Package Manager (NPM)

basics of, 8to install/uninstall and update packages,

9–13NODE_ENV environment variable, 222node_modules folder, loading from, 27node-http-proxy module, 260Node.js

browser-based chatrooms and, 245servers, serving HTML fi les with, 245

node-mysqldata, reading effi ciently, 272–276data, securely adding to databases,

270–272installing, 268libraries for connecting to MySQL

databases, 268–269MySQL application (listing), 274–275

node-tap, 157–158. See also testing modules and applications

node-v.pkg Macintosh installer, 5normalize function (path module), 54NoSQL. See also CouchDB, connecting to

with Nanobasics of, 277document-oriented databases and, 311

notifi cation of child processes exits, 72–73

NPM. See Node Package Manager (NPM)

O

.on() function, binding callbacks and, 38–39

.once() function, executing callbacks and, 40–41

opening fi les, 58OpenSSL library, 140options method attribute, HTTP requests

and, 123

P

package.json fi les, 12–13packages

dependencies and, 11–13NMP basics, 8NPM to install/uninstall and update,

9–13paging, Mongoose and, 318–320parallel

executing in, callback fl ow and, 185–186parallel I/O requests, 320parallelizing requests, 320–321

parsing (Connect)cookies, 212–213query strings, 210–211request body, 211–212

passwords, Express.js login, 232–233path module, 54path.exists() function, 54, 56–57pausing streams, 77Perl, AnyEvent, 17permissions

command failures and, 218error events and, 84installing Express.js and, 218installing Node and, 7installing packages and, 9

pipe() function, slow client problem and, 82

bindex.indd 365bindex.indd 365 21/09/12 4:03 PM21/09/12 4:03 PM

Page 16: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

366

pipes, process.stdin.pipe (conn) – removing

pipes, process.stdin.pipe(conn) command, 107, 110

pipingfi les (HTTP servers), 99–100output (HTTP servers), 100Piping into a socket (listing), 86Piping movies to HTTP response

(listing), 100Piping out a socket (listing), 86into streams, HTTP requests and, 127user input into servers (UDP), 135

placeholdersdatabase security and, 271reading database data and, 272

pooling sockets with http.Agent, 116–118printing server messages (TCP), 107private keys

basics of, 139–140generating, 140HTTPS servers and, 150

process.nextTick function, for deferring function execution, 47–49

process.stdin stream, 107process.stdin.pipe(conn) command,

107, 110programming. See also asynchronous

programmingevent-driven programming and Node,

16–17Node programming limitations, 15–16

public keyscertifi cates, 140cryptography basics, 139–140generating, 140

Pythoninstalling Node and, 6Twisted, 17

Q

queriesad-hoc (Mongoose), 340CouchDB and, 277, 286, 290–291fi le statistics, querying, 57–58

MongoDB and, 312query results, sorting (Mongoose), 317

query stringsbasics of, 210parsing (Connect), 210–211

queuing, async.queue function, 187–189

R

Rails, 217readable streams

assembling, 82basics of, 75, 76–77fi le-system streams, 79networking streams, 80slow client problem and, 80–81

reading, from fi les, 59–61ReadStream function, 61redirects, request module and (HTTP),

121–122Redis

distributing server-side applications using, 259–263

Nano and, 278reducing, array.reduce function, 191–192rejectUnauthorized option (HTTPS), 151relational databases. See also CouchDB,

connecting to with Nanoconnecting to, CouchDB and, 281connecting/communicating with

(MySQL), 268–269data, securely adding to, 270–272vs. document-oriented databases, 311problems with, 277pros and cons, 267, 277reading data effi ciently, 272–276

relative fi le paths, 55.removeAllListeners() function,

removing event listeners using, 41.removeListener() function, removing

event listeners using, 38, 40, 41removing

event listeners, 40–41headers (HTTP servers), 99

bindex.indd 366bindex.indd 366 21/09/12 4:03 PM21/09/12 4:03 PM

Page 17: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

367

request body – schemas (Mongoose)

request bodyencoding (HTTP), 125–127in HTTP, 211parsing (Connect), 211–212

request module for simplifying HTTP requests

basics of, 118cookie jars, 127cookies, 127installing and using, 118–120redirects, 121–122request body, encoding, 125–127request options, 123–125streaming, 127testing server, 120–121

request module, functions, executing in series and, 184

requestCert option (HTTPS), 151requests

HTTPS, 152–153http.ServerRequest object, 97–98parallelizing (Mongoose), 320–321

require function, 24, 25resolving fi le paths, 55response body (HTTP), 116response object attributes (HTTP), 115–116responses

chunked, 116HTTP chunked responses and timers,

102http.serverresponse object, 98–99response body (HTTP servers), 99, 116

responses, streaming chunked responses, 99–100

resuming streams, 77Rogers, Mikeal, 118, 278, 329route listeners

adding, 349Article route listeners (listing), 342–344Completed user route listeners (Express.

js) (listing), 225models, using in route listeners

(Mongoose), 315pages and, 318–320

user creation route listener and (Mongoose), 321–322

router middleware (Express.js), 221routes (Mongoose). See also route listeners

route behavior, modifying, 315–318routes, handling (Express.js)

basics of, 222–223Completed user route listeners

(listing), 225Fake users (listing), 224Load User route middleware, 236New user form template (listing),

227–228New version of routes/index.js (listing),

223New version of session routes (listing),

234–235New version of user routes (listing),

234–235, 237restricting routes, 234User list template (listing), 226User profi le template (listing), 227Users list view (listing), 224Users routes (listing), 223

routing requests (Express.js)basics of, 222route middleware, 234–238routes, handling. See routes, handling

(Express.js)routing tables, 222sessions, 229–233

rows, inserting/updating, 272Ruby’s Event Machine, 17running Node, 8

S

scalable network services, Node and, 3–4scheduling of functions. See functions,

scheduling with timersschemas (Mongoose)

Article schema (listing), 341–342basics of, 314defi ning, 314

bindex.indd 367bindex.indd 367 21/09/12 4:03 PM21/09/12 4:03 PM

Page 18: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

368

scope variables, debugging and – Socket.IO for real-time web applications

scope variables, debugging and, 175scopes, creating functions and, 19Secure Socket Layer (SSL). See also TLS/SSL

for securing TCP serversbasics of, 139OpenSSL library, 140

security, CouchDB and, 301serialization, forcing, 49–50servers

building (HTTPS), 149–152building (UDP), 130–132chat servers. See chat serverscommand line, sending to (TCP), 107connecting to (TCP), 104, 107connecting to (TLS), 143data and (TLS), 144data and (UDP), 135, 136installing and running Socket.IO on,

243–245reconnecting to (TCP), 108–109Redis servers, installing, 260server messages, printing (TCP), 107simple echo server, creating (UDP),

132–133Simple Socket.IO chat server, 247Socket.IO chat server that allows users to

join a room (listing), 257–259Socket.IO chat server that detects

disconnections (listing), 254–255Socket.IO chat server that supports user

login (listing), 251–252Socket.IO chat server that uses a Redis

store (listing), 261–263Socket.IO-based server example (listing),

282–284TCP, defi ned, 103testing server (HTTP request module),

120–121TLS servers, building, 141–142UDP and, 130

server-side applications, distributing, 259–263

server-side TCP socket streams, 76session stores, 213–214, 216

sessionsConnect and, 213–216Express.js and, 229–233Session routes (Express.js), 229–230

setInterval functionfor canceling repetitive function

execution, 47child processes and, 72forcing serialization and, 49–50for repetitive function execution, 45

settersdatabase storage and, 331–332names and, 337virtual attributes and (Mongoose), 333

setTimeout functionfor deferring function execution, 45, 46forcing serialization and, 49–50idle sockets and, 86–87

shallow equality, 160–161, 162shutting down HTTP servers, 101signals, child processes and, 73–74size, of datagrams, 138slicing, buffers, 32slow client problem, 80–82Socket.IO, CouchDB and

Socket.IO-based chat client that formats messages (listing), 292–294

Socket.IO-based chat client that presents avatars (listing), 298–301

Socket.IO-based chat server that presents avatars (listing), 305–309

Socket.IO-based chat server that sends structured message documents (listing), 294–297

Socket.IO-based server example (listing), 282–284

Socket.IO-based server that creates database and view you need (listing), 288–290

Socket.IO for real-time web applicationsbasics of, 241, 243building chats with, 245installing and running on servers,

243–245

bindex.indd 368bindex.indd 368 21/09/12 4:03 PM21/09/12 4:03 PM

Page 19: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

369

socket.keepAlive () call – TCP chat servers, building

Redis and, 260–261Socket.IO client, 244WebSockets basics, 242–243

socket.keepAlive() call, 87sockets

closing (UDP), 134pooling with http.Agent (HTTP),

116–118sockets, TCP servers and

delays/no delays, 87–88idle sockets, 86–87keep-alive functionality, and, 87Piping out a socket (listing), 86socket object basics, 85–86

sorting query results (Mongoose), 317source code

TCP clients, 111–112using to install Node, 6–8

sparse indexes, 340spawning child processes. See child processesSQL injection, defi ned, 270–271squaring of numbers, 183–184standard error stream, child processes and,

70standard input/output and error fi le

descriptors, 53–54static assets, serving (Connect), 209–210static fi les

servers that serve static fi les, building, 101–102

serving (Connect), 209–210static methods, defi ning (Mongoose),

348–349storing

in databases, getters and, 331–332documents (CouchDB), 285user data in persistent databases (Express.

js), 238users in database memory (Express.js),

228streaming

chunked responses, 99–100request module and (HTTP), 127response body (HTTP), 116

stream.pipe() function, slow client problem and, 82

stream.resume() method, 77streams

basics of, 75–76ending of, 77fi le-system streams, 79–80http.request function and, 114networking, 80readable. See readable streamsserver-side TCP socket streams, 76slow client problem and, 80–82standard error stream, child processes

and, 70streaming response body

(HTTP), 116TCP connections and, 103–104writable, 75, 77–78

stream.setEncoding() function, 76strings

= operator, string appearance and, 231

console.log function and, 169event types and, 37query strings, parsing, 210–211

T

tail command, 69tarball URL, 6TCP (transmission control protocol)

basics, 103–104servers, securing. See TLS/SSL for

securing TCP serversTCP servers, defi ned, 103vs. UDP, 129

TCP chat servers, buildingclient connections, accepting, 89–90clients, collecting, 90–91closed connections, removing, 92–93data, broadcasting, 91–92data, reading from connections, 90getting started, 89using chat servers, 93

bindex.indd 369bindex.indd 369 21/09/12 4:03 PM21/09/12 4:03 PM

Page 20: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

370

TCP clients, building – unregistering events

TCP clients, buildingconnections, closing, 105–106data, sending and receiving, 105errors, handling, 106servers, connecting to, 104streams, basics, 103–104

TCP command-line clients, building (example)

client source code, 111–112command line, sending to servers, 107connections, closing, 109–111reconnecting to servers, 108–109server messages, printing, 107servers, connecting to, 107

TCP servers, creatingbasics of, 83–85client connections, listening for, 88delay/no delay, 87–88errors, handling, 88–89idle sockets, 86–87keep-alive functionality, 87servers, closing, 88socket object and, 85–86

templatesArticle detail view and (listings), 345–347Article list partial template (listing), 348modifying (Mongoose), 334–336New user form template, 227–228New user form template (listing), 227–228User list template (listing), 226views/users/index.jade template,

paging and, 318–319testing

chat servers, 93servers (UDP), 131Sum client tests (listing), 165–166testing server (HTTP request module),

120–121testing modules and applications

assert module, 159–161, 162assertion functions in node-tap, 161–163asynchronous modules, 163–166node-tap basics, 157–158tests, running, 159tests, writing, 158–159

threads, 15–16ticks, defi ned, 47time, tracking (Mongoose), 338–339timeouts, idle sockets and, 86–87timers

HTTP chunked responses and, 102scheduling with. See functions,

scheduling with timerstls.connect function, 143, 144TLS/SSL for securing TCP servers

basics of, 139private/public keys, 139–140TLS chat servers, creating, 145–146TLS clients, building, 143–145TLS command-line chat client, creating,

146–148TLS servers, building, 141–142

transmission control protocol (TCP). See TCP (transmission control protocol)

Transport Layer Security (TLS). See TLS/SSL for securing TCP servers

truthy values, 159–160, 162Twisted (Python), 17Twitter, asynchronous validators and,

328–330

U

UDP (User Datagram Protocol)basics of, 129–130clients, building, 134multicast, 136–138servers, building, 130–132simple command-line client, creating,

135–136simple echo server, creating, 132–133vs. TCP, 129

uninstalling modules, 10–11unique indexes, 340UNIX

fopen UNIX manual page, 58installing Node on, 6–8Node fi les and, 53signals and their options, 66–67

unregistering events, 40

bindex.indd 370bindex.indd 370 21/09/12 4:03 PM21/09/12 4:03 PM

Page 21: INDEX [] · async.forEach Iterating over a collection using (listing), 189–190 ordering of results and, 188 asynchronous dependencies, 320 asynchronous middleware, 200–201 asynchronous

371

updating – writing

updatingmodules, 11packages. See Node Package Manager

(NPM)URLs, req.url property (http

.ServerRequest object), 97.use() method, adding middleware to

servers and, 207User Datagram Protocol. See UDP (User

Datagram Protocol)users

New middleware to restrict user to session user (listing), 238

New user form template (listing), 227–228

separating into chat rooms, 255–259User Partial for Headers (listing),

230–231User profi le template (listing), 227User profi le template using full_name

virtual attribute/nlin views/users/profi le.jade (listing), 335

User profi le template using twitter_url virtual attribute in/nlviews/users/profi le.jade (listing), 332–333

users/profi le template (Express.js), 226UTF-8-encoding

buffers and, 30, 32–33streams and, 77

util.format function, 168

V

validatingage (Mongoose), 327–328certifi cates (HTTPS), 151–152, 153–154email fi elds (Mongoose), 324

validators, using (Mongoose), 324–330value assignment (node-mysql), 271–272values

default (Mongoose), 338–339of fi elds, combining, 341truthy and falsy, 159–160

var keyword, debugging and, 172variables, storing, 18

verbs (HTTP), 114–115, 118–119versioning, CouchDB and, 287versions of Node, 6views. See CouchDB viewsvirtual attributes (Mongoose), 332–338

W

waterfall, async.waterfall function, 186web applications. See Express.js for web

applicationsweb chats, HTTP and, 241–242. See also

chats, building with Socket.IOwebsites for downloading

Node, 4tarball URL, 6wget, 6

websites for further informationinstalling CouchDB, 278installing Redis servers, 260IrisCouch, 281MongoDB, 312MongoHQ, 312Node, 4node-http-proxy module, 260public modules, 9third-party middleware components, 216

WebSocketsbasics of, 242–243HTTP and real-time applications and,

242wget, installing Node and, 6Windows, installing Node on, 4–5writable streams

assembling, 82basics of, 75, 77–78fi le writable streams, 80networking streams, 80slow client problem and, 80

WriteStream function, 61writing

to fi les, 60headers (HTTP servers), 98response body (HTTP servers), 99tests, 158–159

bindex.indd 371bindex.indd 371 21/09/12 4:03 PM21/09/12 4:03 PM