Learning Node.js
Learning Node.jsA Hands-On Guide toBuilding Web Applications inJavaScriptAuthor:Marc WandschneiderAddison-Wesley Learning SeriesLEARNING JavascriptOBJECTIVEC 2.0 LEARNING COCOS2DLEARNIN0ANDR。1D0 AME PR。 GRAMMIN0Rob sAugoROBERT C÷ Addison- WesleyVisit informit. com/learningseries for a complete list of available publicationsThe Addison-Wesley Learning Series is a collection of hands-on programmingguides that help you quickly learn a new technology or language so you canapply what you' ve learned right away.Each title comes with sample code for the application or applications built inthe text. This code is fully annotated and can be reused in your own projectswith no strings attached many chapters end with a series of exercises toencourage you to reexamine what you have just learned and to tweak oradjust the code as a way of learningTitles in this series take a simple approach: they get you going right away andleave you with the ability to walk off and build your own application and applythe language or technology to whatever you are working onA Addison -Wesley nformITSafariLWAYS LEARNINGPEARSONwww.it-ebooks.infoLearning Node jsa Hands-On Guide toBuilding Web Applications inJavascriptMarc Wandschneiderw Addison-WesleyUpper Saddle river, NJ. Boston. Indianapolis San FranciscoNew york· Toronto· Montreal· London· Munich· Paris· MadridCape Town· Sydney· Tokyo· Singapore· Mexico Citywww.it-ebooks.infoMany of the designations used by manufacturers and sellers to distinguish their productsEditor-in -Chiefare claimed as trademarks. Where those designations appear in this book, and theMark taubpublisher was aware of a trademark claim, the designations have been printed with initialcapital letters or in all capitals.Acquisitions EditorMark TaubThe author and publisher have taken care in the preparation of this book, but make noMarketingexpressed or implied warranty of any kind and assume no responsibility for errors orManageomissions. No liability is assumed for incidental or consequential damages in connectionStephane Nakibwith or arising out of the use of the information or programs contained hereinManaging EditorThe publisher offers excellent discounts on this book when ordered in quantity for bulkKristy Hartpurchases or special sales, which may include electronic versions and/ or custom coversand content particular to your business, training goals, marketing focus, and brandingSenior ProjectEditorinterests. For more information, please contactLori lyU.s. Corparate and Government salesCopy Editor(800)3823419Chuck Hutchinsoncorpsales@pearsontechgroup.comIndexerFor sales outside the United States, please contactTim WrightInternational salesProofreaderinternational@pearsoned comVisit us on the Web: informit. com/ awTechnical ReviewerBill GloverLibrary of Congress Control Number: 2013936406Editorial AssistantCopyright o 2013 Pearson Education, Inc.Olivia BasegioAll rights reserved. Printed in the United States of America. This publication is protectedCover Designerby copyright, and permission must be obtained from the publisher prior to any prohibitedChuti Prasertsithreproduction, storage in a retrieval system or transmission in any form or by any meanselectronic, mechanical, photocopying, recording, or likewise. To obtain permission toCompositorNonie ratcliffuse material from this work, please submit a written request to Pearson Education, Inc.Permissions Department, one Lake street Upper saddle river, New Jersey 07458, or youmanufacturingmay fax your request to(201)236-3290luyerDan UhriglsBN-13:9780-32191057-8SBN10:032191057-5Text printed in the United states on recycled paper at rR donnelley sons,Crawfordsville, IndianFirst printing: June 2013www.it-ebooks.infoMuch love to Tina, for simply being therewww.it-ebooks.infoThis page intentionally left blankwww.it-ebooks.infoTable of contentsIntroduction 1Why Node. js? 1The Web 1New Technologies 2What Exactly Is Node. js? 2Who Is this book for? 4How to Use This book 4Download the source code 5Part I: Learning to Walk 71 Getting Started 9stalling Node s 9Installation on windows 9Installation on the mac 12Installation on linux 14ning Node. js and"Hello World! 16The node shell 16Editing and Running Javascript Files 17Your first web server 17Debugging Your Node. js Programs 19Staying Up-to-Date and Finding Help 22Summary 232 A Closer Look at JavaScript 25Types 25Type Basics 26Constants 26Numbers 27Booleans 28Strings 29Objects 32Arrays 34www.it-ebooks.infoContentsType Comparisons and Conversions 38Functions 39Basics 39Function Scope 42Language Constructs 43Classes, Prototypes, and Inheritance 44Prototypes and Inheritance 45Errors and Exceptions 47Some Important Node js globals 47global 47console 48process 48Summary 483 Asynchronous Programming 49The old Way of Doing Things 49The Node. js Way of doing things 50Error Handling and Asynchronous Functions 53The callback Function and Error Handling 54Who Am I? Maintaining a Sense of ldentity 56Being Polite--Learning to Give Up Control 58Synchronous Function Calls 61Summary 61Part II: Learning to Run 634 Writing Simple Applications 65Your first json server 65Returning Some Data 67Node Pattern: Asynchronous Loops 69Learning to Juggle: Handling More Requests 72More on the request and response Objects 78Increased flexibility GET Params 79Moditying Things: POST Data 83Receiving JSoN POST Data 84Receiving Form POST Data 87Summary 88www.it-ebooks.infoContent5 Modules 89Writing Simple Modules 89Modules and objects 91pm: The Node Package Manager 92Consuming Modules 93Searching for Modules 93le Caching 94Cycles 95Writing Modules 95Creating Your Module 96Developing with Your Module 101Publishing Your Modules 102A Module so common t should be built in 103The problem 104The solution 105Summary 1126 Expanding Your Web Server 113Serving Static Content with Streams 113Reading a File 114Serving Static Files in a Web Server with Buffers 116Serving Up More Than Just HTML 118Assembling Content on the Client: Templates 120The hTMl skeleton p123Static Content 124Modifying Your URL Scheme 124The JavaScript Loader/Bootstrapper 126Templating with Mustache 127Your Home Page Mustache Template 129Putting It All Together 130Summary 133Part Ill Writing Web Applications 1357 Building Web Applications with Express 137Installing Express 137Hello world in Express 138www.it-ebooks.info