The Capabilities of Node.Js
Total Page:16
File Type:pdf, Size:1020Kb
Node.js Web Development Third Edition Create real-time server-side applications with this practical, step-by-step guide David Herron BIRMINGHAM - MUMBAI Node.js Web Development Third Edition Copyright © 2016 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2011 Second published: July 2013 Third edition: June 2016 Production reference: 1220616 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78588-150-3 www.packtpub.com Credits Author Project Coordinator David Herron Sanchita Mandal Reviewer Proofreader Nicholas Duffy Safis Editing Commissioning Editor Indexer Amarabha Banerjee Mariammal Chettiyar Acquisition Editor Graphics Larissa Pinto Disha Haria Content Development Editor Production Coordinator Samantha Gonsalves Manu Joseph Technical Editor Cover Work Vivek Pala Manu Joseph Copy Editor Pranjali Chury About the Author David Herron has worked as a software engineer in Silicon Valley for over 20 years. This includes companies both tiny and large. He has worked on a wide variety of projects, from an X.400 e-mail server and client application to assisting with the launch of the OpenJDK project (open source Java rocks), to Yahoo's Node.js application-hosting platform (Mojito and Manhattan), and applications to monitor solar power array performance. While a staff engineer at Sun Microsystems, David worked as the architect of the Java SE Quality Engineering team where he focused on test automation tools, including co-developing the AWT Robot class. He was involved in open source activities related to Java, including the OpenJDK project. Before Sun, he worked for VXtreme on software which eventually became Windows Media Player when Microsoft bought the company. At Mainsoft, David worked on a library that allowed developers to recompile Windows applications on Unix, and then participated in porting Internet Explorer to Unix. At The Wollongong Group, he worked on both e-mail client and server software and was part of several IETF working groups improving e-mail-related protocols. David is interested in electric vehicles, world energy supplies, climate change, and environmental issues, and he is a co-founder of Transition Silicon Valley. As an online journalist, he writes about electric cars and other green technology on LongTailPipe.com after having written for PlugInCars.com. He runs a large electric vehicle discussion website on VisForVoltage.org, and he blogs about other topics, including Node.js, Drupal, and Doctor Who on DavidHerron.com. Using Node.js, he developed a Content Management System that produces static HTML websites or EPUB3 eBooks, AkashaCMS (akashacms.com). There are many people I am grateful to. I wish to thank my mother, Evelyn, for, well everything; my father, Jim; my sister, Patti; and my brother, Ken. What would life be without all of you? I wish to thank my girlfriend, Maggie, for being there and encouraging me, her belief in me, her wisdom, and humor. May we have many more years of this. I wish to thank Dr. Ken Kubota of the University of Kentucky for believing in me and giving me my first job in computing. It was six years of learning not just the art of computer system maintenance, but so much more. I wish to thank my former employers, University of Kentucky Mathematical Sciences Department, The Wollongong Group, MainSoft, VXtreme, Sun Microsystems, Yahoo!, Recargo, Laplace Systems, and all the people I worked with in each company. I am grateful to Ryan Dahl, the creator of Node.js, and the current Node.js core team members. They have the rare combination of wisdom and vision needed to create such a joy-filled fluid software development platform. Some platforms are just plain hard to work with, but not this one. About the Reviewer Nicholas Duffy has had a wide-ranging career, holding positions from analyst to business intelligence architect, to software engineer, and even golf professional. He has a passion for all things data and software engineering, specializing in data warehouse architecture, Python, and Node.js. He is a frequent contributor to open source projects and is, unfortunately, also a lifelong New York Mets fan. You can read more about Nicholas' interests on this blog at https://medium.com/@duffn or contact him via GitHub at @duffn. I'd like to thank my wife, Anne, and boys, Jack and Chuck, for their never ending support in whatever endeavor. www.PacktPub.com eBooks, discount offers, and more Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Table of Contents Preface vii Chapter 1: About Node.js 1 The capabilities of Node.js 3 Server-side JavaScript 3 Why should you use Node.js? 4 Popularity 4 JavaScript at all levels of the stack 4 Leveraging Google's investment in V8 5 Leaner asynchronous event-driven model 5 Microservice architecture 5 The Node.js is stronger for having survived a major schism and hostile fork 5 Performance and utilization 8 Is Node.js a cancerous scalability disaster? 9 Server utilization, the bottom line, and green web hosting 11 Node.js, the microservice architecture, and easily testable systems 12 Node.js and the Twelve-Factor app model 13 Summary 13 Chapter 2: Setting up Node.js 15 System requirements 15 Installing Node.js using package managers 16 Installing on Mac OS X with MacPorts 16 Installing on Mac OS X with Homebrew 17 Installing on Linux, *BSD, or Windows from package management systems 17 Installing the Node.js distribution from nodejs.org 18 Table of Contents Installing from source on POSIX-like systems 19 Installing prerequisites 19 Native code modules and node-gyp 20 Installing developer tools on Mac OS X 21 Installing from source for all POSIX-like systems 22 Installing development instances with nvm 23 Node.js versions policy and what to use 25 Running and testing commands 26 Node.js's command-line tools 26 Running a simple script with Node.js 28 Launching a server with Node.js 29 NPM – the Node.js package manager 30 Node.js and ECMAScript 6 (ES-2015, ES-2016, and so on) 31 Using Babel to use experimental JavaScript features 33 Summary 35 Chapter 3: Node.js Modules 37 Defining a module 37 Node.js module format 39 File modules 39 Demonstrating module-level encapsulation 40 Directories as modules 41 Node.js's algorithm for require (module) 42 Module identifiers and path names 42 An example application directory structure 44 npm – the Node.js package management system 45 The npm package format 45 Finding npm packages 47 Other npm commands 49 Installing an npm package 49 Initializing a new npm package 50 Maintaining package dependencies with npm 51 Fixing bugs by updating package dependencies 52 Declaring Node.js version compatibility 53 Updating outdated packages you've installed 53 Installing packages from outside the npm repository 54 Publishing an npm package 54 Package version numbers 55 A quick note about CommonJS 57 Summary 57 [ ii ] Table of Contents Chapter 4: HTTP Servers and Clients – A Web Application's First Steps 59 Sending and receiving events with EventEmitters 60 The EventEmitter theory 61 HTTP server applications 62 ES-2015 multiline and template strings 65 HTTP Sniffer – listening to the HTTP conversation 67 Web application frameworks 69 Getting started with Express 70 Walking through the default Express application 74 The Express middleware 76 Middleware and request paths 77 Error handling 79 Calculating the Fibonacci sequence with an Express application 79 Computationally intensive code and the Node.js event loop 84 Algorithmic refactoring 86 Making HTTP Client requests 88 Calling a REST backend service from an Express application 91 Implementing a simple REST server with Express 91 Refactoring the Fibonacci application for REST 95 Some RESTful modules and frameworks 97 Summary 97 Chapter 5: Your First Express Application 99 ES-2015 Promises and Express router functions 99