Learning Node Shelley Powers
Total Page:16
File Type:pdf, Size:1020Kb
www.allitebooks.com www.allitebooks.com Learning Node Shelley Powers Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo www.allitebooks.com Learning Node by Shelley Powers Copyright © 2012 Shelley Powers. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editor: Simon St. Laurent Indexer: Aaron Hazelton, BIM Publishing Services Production Editor: Rachel Steely Cover Designer: Karen Montgomery Copyeditor: Rachel Monaghan Interior Designer: David Futato Proofreader: Kiel Van Horn Illustrators: Robert Romano and Rebecca Demarest September 2012: First Edition. Revision History for the First Edition: 2012-08-24 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449323073 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Learning Node, the image of a hamster rat, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-1-449-32307-3 [LSI] 1345837731 www.allitebooks.com Table of Contents Preface . .................................................................... ix 1. Node.js: Up and Running . ................................................ 1 Setting Up a Node Development Environment 2 Installing Node on Linux (Ubuntu) 2 Partnering Node with WebMatrix on Windows 7 4 Updating Node 9 Node: Jumping In 10 Hello, World in Node 10 Hello, World from the Top 11 Asynchronous Functions and the Node Event Loop 13 Reading a File Asynchronously 14 Taking a Closer Look at Asynchronous Program Flow 16 Benefits of Node 19 2. Interactive Node with REPL . ............................................. 21 REPL: First Looks and Undefined Expressions 21 Benefits of REPL: Getting a Closer Understanding of JavaScript Under the Hood 23 Multiline and More Complex JavaScript 24 REPL Commands 27 REPL and rlwrap 28 Custom REPL 29 Stuff Happens—Save Often 32 3. The Node Core . ........................................................ 35 Globals: global, process, and Buffer 35 global 36 process 38 Buffer 39 The Timers: setTimeout, clearTimeout, setInterval, and clearInterval 40 iii www.allitebooks.com Servers, Streams, and Sockets 41 TCP Sockets and Servers 42 HTTP 44 UDP/Datagram Socket 46 Streams, Pipes, and Readline 48 Child Processes 50 child_process.spawn 50 child_process.exec and child_process.execFile 52 child_process.fork 53 Running a Child Process Application in Windows 53 Domain Resolution and URL Processing 54 The Utilities Module and Object Inheritance 56 Events and EventEmitter 59 4. The Node Module System . .............................................. 63 Loading a Module with require and Default Paths 63 External Modules and the Node Package Manager 65 Finding Modules 69 Colors: Simple Is Best 71 Optimist: Another Short and Simple Module 72 Underscore 73 Creating Your Own Custom Module 74 Packaging an Entire Directory 75 Preparing Your Module for Publication 75 Publishing the Module 78 5. Control Flow, Asynchronous Patterns, and Exception Handling . 81 Promises, No Promises, Callback Instead 81 Sequential Functionality, Nested Callbacks, and Exception Handling 84 Asynchronous Patterns and Control Flow Modules 91 Step 92 Async 95 Node Style 100 6. Routing Traffic, Serving Files, and Middleware . 103 Building a Simple Static File Server from Scratch 103 Middleware 110 Connect Basics 111 Connect Middleware 113 Custom Connect Middleware 118 Routers 121 Proxies 123 iv | Table of Contents www.allitebooks.com 7. The Express Framework . ............................................... 127 Express: Up and Running 128 The app.js File in More Detail 129 Error Handling 132 A Closer Look at the Express/Connect Partnership 133 Routing 134 Routing Path 136 Routing and HTTP Verbs 139 Cue the MVC 145 Testing the Express Application with cURL 150 8. Express, Template Systems, and CSS . 153 The Embedded JavaScript (EJS) Template System 153 Learning the Basic Syntax 154 Using EJS with Node 155 Using the EJS for Node Filters 157 Using a Template System (EJS) with Express 158 Restructuring for a Multiple Object Environment 160 Routing to Static Files 161 Processing a New Object Post 163 Working with the Widgets Index and Generating a Picklist 165 Showing an Individual Object and Confirming an Object Deletion 166 Providing an Update Form and Processing a PUT Request 168 The Jade Template System 172 Taking the Nickel Tour of the Jade Syntax 172 Using block and extends to Modularize the View Templates 174 Converting the Widget Views into Jade Templates 176 Incorporating Stylus for Simplified CSS 180 9. Structured Data with Node and Redis . 187 Getting Started with Node and Redis 188 Building a Game Leaderboard 190 Creating a Message Queue 196 Adding a Stats Middleware to an Express Application 201 10. Node and MongoDB: Document-Centric Data . 207 The MongoDB Native Node.js Driver 208 Getting Started with MongoDB 208 Defining, Creating, and Dropping a MongoDB Collection 209 Adding Data to a Collection 210 Querying the Data 213 Using Updates, Upserts, and Find and Remove 217 Implementing a Widget Model with Mongoose 221 Table of Contents | v www.allitebooks.com Refactoring the Widget Factory 222 Adding the MongoDB Backend 223 11. The Node Relational Database Bindings . 229 Getting Started with db-mysql 230 Using Query String or Chained Methods 230 Updating the Database with Direct Queries 233 Updating the Database with Chained Methods 236 Native JavaScript MySQL Access with node-mysql 237 Basic CRUD with node-mysql 237 MySQL Transactions with mysql-queues 239 ORM Support with Sequelize 242 Defining a Model 242 Using CRUD, ORM Style 244 Adding Several Objects Easily 246 Overcoming Issues Related to Going from Relational to ORM 247 12. Graphics and HTML5 Video . ............................................ 249 Creating and Working with PDFs 249 Accessing PDF Tools with Child Processes 250 Creating PDFs with PDFKit 258 Accessing ImageMagick from a Child Process 260 Properly Serving HTML5 Video with HTTP 264 Creating and Streaming Canvas Content 268 13. WebSockets and Socket.IO . ............................................ 273 WebSockets 273 An Introduction to Socket.IO 274 A Simple Communication Example 274 WebSockets in an Asynchronous World 278 About That Client Code 279 Configuring Socket.IO 279 Chat: The WebSockets “Hello, World” 281 Using Socket.IO with Express 284 14. Testing and Debugging Node Applications . 287 Debugging 287 The Node.js Debugger 287 Client-Side Debugging with Node Inspector 290 Unit Testing 292 Unit Testing with Assert 292 Unit Testing with Nodeunit 296 Other Testing Frameworks 297 vi | Table of Contents www.allitebooks.com Acceptance Testing 301 Selenium Testing with Soda 301 Emulating a Browser with Tobi and Zombie 305 Performance Testing: Benchmarks and Load Tests 306 Benchmark Testing with ApacheBench 307 Load Testing with Nodeload 311 Refreshing Code with Nodemon 313 15. Guards at the Gate ... ................................................. 315 Encrypting Data 316 Setting Up TSL/SSL 316 Working with HTTPS 317 Safely Storing Passwords 319 Authentication/Authorization with Passport 322 Authorization/Authentication Strategies: OAuth, OpenID, Username/ Password Verification 323 The Local Passport Strategy 324 The Twitter Passport Strategy (OAuth) 331 Protecting Applications and Preventing Attacks 337 Don’t Use eval 338 Do Use Checkboxes, Radio Buttons, and Drop-Down Selections 338 Scrub Your Data and Sanitize It with node-validator 339 Sandboxed Code 340 16. Scaling and Deploying Node Applications . 345 Deploying Your Node Application to Your Server 345 Writing That package.json File 346 Keeping Your Application Alive with Forever 349 Using Node and Apache Together 351 Improving Performance 353 Deployment to a Cloud Service 353 Deploying to Windows Azure via Cloud9 IDE 354 Joyent Development SmartMachines 356 Heroku 357 Amazon EC2 357 Nodejitsu 357 Appendix: Node, Git, and GitHub . 359 Index . 363 Table of Contents | vii www.allitebooks.com www.allitebooks.com Preface Not Your Ordinary JavaScript You picked the perfect time to learn Node. The technology evolving around Node is still young and vibrant, with interesting new variations and twists popping up on a regular basis. At the same time, the technology has reached a level of maturity that assures you your time learning Node will be well spent: installation has never been easier, even on Windows; the “best of breed” modules are beginning to surface from the seeming hundreds available for use; the infrastructure is becoming robust enough for production use. There are two important things to keep in mind when you work with Node. The first is that it is based in JavaScript, more or less the