i Node.js: Novice to Ninja Copyright © 2022 SitePoint Pty. Ltd. Product Manager:Simon Mackie Technical Editor:Ivaylo Gerchev English Editor:Ralph Mason Cover Designer:Alex Walker Notice of Rights 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 embodied in critical articles or reviews. Notice of Liability The author and publisher have made every effort to ensure the accuracy of the information herein. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors and SitePoint Pty. Ltd., nor its dealers or distributors will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software or hardware products described herein. Trademark Notice Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark. Published by SitePoint Pty. Ltd. 10-12 Gwynne St, Richmond, VIC, 3121 Australia Web: www.sitepoint.com Email: [email protected] ISBN 978-1-925836-52-3 (print) ISBN 978-1-925836-53-0 (ebook) Printed and bound in the United States of America ii Node.js: Novice to Ninja About Craig Buckler Craig is a UK-based freelance full-stack web developer, writer, and speaker who’s passionate about standards and performance. He began coding in the 1980s and started client-side JavaScript development on its release in 1995 when DHTML, spacer GIFs, and marquees were considered sophisticated. You may have encountered his work at SitePoint, where he’s written more than 1,200 tutorials, and books includingJump Start Web Performance,Browser DevTool Secrets, andDocker for Web Developers. Craig used Node.js from the start and hopes this book is a great first step on your server-side JavaScript journey. Contact him on Twitter @craigbuckler or at craigbuckler.com. About SitePoint SitePoint specializes in publishing fun, practical, and easy-to-understand content for web professionals. Visithttps://www.sitepoint.com/to access our blogs, books, newsletters, articles, and community forums. You’ll find a stack of information on JavaScript, PHP, Ruby, mobile development, design, and more. Table of Contents iii Table of Contents Preface .........................................................................................xvii Chapter 1: What is Node.js?..................................1 Why Learn Node.js?...........................................................................3 It’s JavaScript.............................................................................3 It’s Fast..........................................................................................4 It’s Real-time..............................................................................5 It’s Lightweight.........................................................................5 It’s Modular.................................................................................5 It’s Extendible............................................................................5 It’s Open Source......................................................................6 It’s Everywhere.........................................................................6 Summary.................................................................................................7 Quiz............................................................................................................7 Chapter 2: Install Node.js........................................9 Choosing a Node.js Version.........................................................11 iv Node.js: Novice to Ninja How to Install Node.js on Linux (or Windows WSL2).......11 Configuring npm Global Permissions on Linux.......12 How to Install Node.js on macOS..............................................13 How to Install Node.js on Windows........................................14 How to Install Node.js on Other Devices..............................14 Run JavaScript Commands in the Node.js REPL..............14 Summary..............................................................................................16 Quiz.........................................................................................................16 Chapter 3: Your First Node.js Application ................................................................................18 Your First Console App..................................................................19 Your First Web Server App..........................................................25 Restarting Node.js Applications with Nodemon...............32 Web Application Considerations..............................................33 Summary..............................................................................................35 Quiz.........................................................................................................36 Chapter 4: How to Debug Node.js Scripts .............................................................................................38 Table of Contents v What is Debugging?.......................................................................39 How to Avoid Bugs..........................................................................39 Use a Good Code Editor....................................................39 Use a Code Linter.................................................................40 Use Source Control.............................................................42 Adopt an Issue-tracking System...................................42 Use Test-driven Development.......................................43 Node.js Debugging Environment Variables........................43 Node.js Debugging Command-line Options......................44 Console Debugging........................................................................44 Node.js util.debuglog.....................................................................47 Debugging with Logging Modules..........................................47 Node.js V8 Inspector......................................................................48 Debugging Node.js Apps with Chrome.................................49 Debugging Node.js Apps with VS Code...............................53 Advanced Debugging Configuration..........................56 Other Node.js Debugging Tools................................................58 Exercise: Debugging webhello.js.............................................59 Summary..............................................................................................61 Debugging Terminology...................................................62 vi Node.js: Novice to Ninja Quiz.........................................................................................................64 Chapter 5: Getting Started with Express ................................................................................................................66 Why use Express?...........................................................................67 Create a New Node.js Project...................................................68 Switch to ES6 Modules.................................................................70 Install Express.....................................................................................71 Create the Express Entry Script................................................73 Should You Switch to HTTPS?...................................................77 Serve Static Files..............................................................................78 Express Middleware Functions.................................................81 Define Working Directories.........................................................82 Compressing HTTP Responses................................................84 Disable Express Identification....................................................85 Handle 404 Not Found Errors...................................................86 Add an HTML Template Engine...............................................86 Advanced Routing...........................................................................91 Routing Path Expressions.................................................91 Routing Path Parameters..................................................92 Table of Contents vii HTTP Route Methods.........................................................92 Creating a Route Handler.................................................93 Exercises..............................................................................................99 Summary..............................................................................................99 Quiz.........................................................................................................99 Chapter 6: Processing Form Data with Express .........................................................................................101 Processing HTTP GET Query Strings....................................103 Processing HTTP Post Body Data..........................................107 Processing Uploaded Files........................................................111 Exercises............................................................................................117 Summary............................................................................................118 Quiz.......................................................................................................118 Chapter 7: How to Use the npm Node Package Manager ............................................................120 Global vs Local Packages..........................................................121 npm Help...........................................................................................122 npm Configuration.........................................................................123 viii Node.js: Novice to Ninja Project Initialization.......................................................................123 Semantic Versioning.........................................................127 Project Dependencies......................................................127 Development Dependencies........................................127 Searching for Packages..............................................................128 Installing Packages.......................................................................130 Semantic Constraints.......................................................131 “No-install” Execution..................................................................132 Listing Packages............................................................................133 Finding Outdated Packages.....................................................136 Removing Packages.....................................................................137 Using npm Scripts.........................................................................138 Special Scripts.....................................................................139 Pre and Post Scripts.........................................................140 Life Cycle Scripts...............................................................140 Sophisticated Scripting...................................................140 Publishing Packages....................................................................142 Publishing Tips....................................................................144 Exercises............................................................................................144 Summary............................................................................................145 Table of Contents ix Quiz.......................................................................................................145 Chapter 8: Using ES2015 and CommonJS Modules .....................................................147 CommonJS........................................................................................149 ES2015 Modules (ESM)................................................................151 Comparison of CommonJS and ES2015 Modules..........155 Importing CommonJS Modules in ES2015........................157 Requiring ES2015 Modules in CommonJS.........................157 Using ES2015 Modules in Browsers......................................157 Summary............................................................................................158 Quiz.......................................................................................................159 Chapter 9: Asynchronous Programming in Node.js ...................................................................................161 Single-threaded Non-blocking I/O Event-looping What?...................................................................................................162 Callbacks in Action...........................................................164 The Event Loop...............................................................................165 Callback Conundrums................................................................166