(This page has no text content)
Server Request Express.js + Middleware express.RouterURL: /users/123 Method: GET params: {_id:123} Response Status: 200 Cookie: _j0n.W3x1eR Content-type: text/html app.use() Defines the way requests to certain URLs are handled Encookie-parser crypts and decrypts info about a user’s status on app Translates request contents to validate or modify dataexpress.json Authenticates user login information during app usepassport express-ejs- layouts Renders web page The EJS templating engine transforms dynamic data and layouts to produce an HTML page in the server’s response. Mongoose is an object document modeling (ODM) library that simplifies your inter- action between the Node.js server and MongoDB database. Mongoose.jsEJS
Get Programming with Node.js
(This page has no text content)
Get Programming with Node.js Jonathan Wexler Foreword by Kyle Simpson MANNING Shelter Island
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2019 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Development editor: Toni Arritola Technical development editor: John Guthrie Review editor: Aleksandar Dragosavljević Production editor: David Novak Copyeditor: Kathy Simpson Proofreader: Melody Dolab Senior technical proofreader: Srihari Sriharan Technical proofreader: German Frigerio Typesetter: Dottie Marsico Cover designer: Monica Kamsvaag Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 ISBN 9781617294747 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – SP – 24 23 22 21 20 19
To the ones who got me programming and to my parents (the two people I always know aren’t reading my book), with love.
(This page has no text content)
ContentsForeword xv Preface xvii Acknowledgments xix About this book xxi About the author xxix Unit 0 GETTING SET UP 1 Lesson 0 Setting up Node.js and the JavaScript engine 3 What you’re going to learn 3 Understanding Node.js 5 Why learn to develop in Node.js? 9 Preparing yourself for this book 10 Summary 11 Lesson 1 Configuring your environment 12 Installing Node.js 12 Installing a text editor 16 Setting up SCM and deployment tools 17 Working with the Node.js REPL in terminal 19 Summary 21 Lesson 2 Running a Node.js application 22 Creating a JavaScript file 23 Running your JavaScript file with Node.js 24 Running individual JavaScript commands 25 Summary 27vii
viii ContentsUnit 1 GETTING STARTED WITH NODE.JS 29 Lesson 3 Creating a Node.js module 31 Running npm commands 33 Initializing a Node.js application 35 Summary 39 Lesson 4 Building a simple web server in Node.js 40 Understanding web servers 41 Initializing the application with npm 43 Coding the application 43 Running the application 47 Summary 48 Lesson 5 Handling incoming data 49 Reworking your server code 50 Analyzing request data 51 Adding routes to a web application 55 Summary 58 Lesson 6 Writing better routes and serving external files 59 Serving static files with the fs module 60 Serving assets 64 Moving your routes to another file 67 Summary 72 Lesson 7 Capstone: Creating your first web application 73 Initializing the application 74 Understanding application directory structure 75 Creating main.js and router.js 76 Creating views 79 Adding assets 80 Creating routes 81 Summary 83 Unit 2 EASIER WEB DEVELOPMENT WITH EXPRESS.JS 85 Lesson 8 Setting up an app with Express.js 87 Installing the Express.js package 88 Building your first Express.js application 90
ixContents Working your way around a web framework 92 Summary 94 Lesson 9 Routing in Express.js 95 Building routes with Express.js 96 Analyzing request data 98 Using MVC 101 Summary 105 Lesson 10 Connecting views with templates 106 Connecting a templating engine 107 Passing data from your controllers 110 Setting up partials and layouts 111 Summary 113 Lesson 11 Configurations and error handling 114 Modifying your start script 115 Handling errors with Express.js 116 Serving static files 119 Summary 119 Lesson 12 Capstone: Enhancing the Confetti Cuisine site with Express.js 121 Initializing the application 121 Building the application 123 Adding more routes 124 Routing to views 125 Serving static views 127 Passing content to the views 128 Handling the errors 129 Summary 131 Unit 3 CONNECTING TO A DATABASE 133 Lesson 13 Setting up a MongoDB database 135 Setting up MongoDB 136 Running commands in the MongoDB shell 140 Connecting MongoDB to your application 144 Summary 146 Lesson 14 Building models with Mongoose 147 Setting up Mongoose with your Node.js application 148 Creating a schema 149 Organizing your models 151 Summary 153
x ContentsLesson 15 Connecting controllers and models 155 Creating a controller for subscribers 156 Saving posted data to a model 159 Using promises with Mongoose 162 Summary 166 Lesson 16 Capstone: Saving user subscriptions 167 Setting up the database 168 Modeling data 168 Adding subscriber views and routes 171 Summary 173 Unit 4 BUILDING A USER MODEL 175 Lesson 17 Improving your data models 177 Adding validations on the model 178 Testing models in REPL 182 Creating model associations 184 Populating data from associated models 188 Summary 192 Lesson 18 Building the user model 193 Building the user model 194 Adding CRUD methods to your models 199 Building the index page 202 Cleaning up your actions 205 Summary 206 Lesson 19 Creating and reading your models 208 Building the new user form 209 Creating new users from a view 211 Reading user data with show 214 Summary 218 Lesson 20 Updating and deleting your models 219 Building the edit user form 220 Updating users from a view 223 Deleting users with the delete action 226 Summary 229 Lesson 21 Capstone: Adding CRUD models to Confetti Cuisine 230 Getting set up 231 Building the models 231
xiContentsCreating the views 237 Structuring routes 242 Creating controllers 243 Summary 247 Unit 5 AUTHENTICATING USER ACCOUNTS 249 Lesson 22 Adding sessions and flash messages 251 Setting up flash message modules 252 Adding flash messages to controller actions 254 Summary 258 Lesson 23 Building a user login and hashing passwords 260 Implementing the user login form 261 Hashing passwords 265 Adding validation middleware with express-validator 269 Summary 272 Lesson 24 Adding user authentication 274 Implementing Passport.js 275 Modifying the create action to use passport registration 279 Authenticating users at login 280 Summary 284 Lesson 25 Capstone: Adding user authentication to Confetti Cuisine 285 Getting set up 286 Creating a login form 286 Adding encryption with Passport.js 288 Adding flash messaging 289 Adding validation middleware with express-validator 291 Adding authentication with Passport.js 293 Logging in and out 294 Summary 296 Unit 6 BUILDING AN API 297 Lesson 26 Adding an API to your application 299 Organizing your routes 300 Creating an API 304
xii Contents Calling your API from the client 306 Summary 310 Lesson 27 Accessing your API from your application 311 Applying an API namespace 312 Joining courses via modal 315 Creating an API endpoint to connect models 318 Summary 321 Lesson 28 Adding API security 323 Implementing simple security 324 Adding API tokens 325 Using JSON web tokens 328 Summary 333 Lesson 29 Capstone: Implementing an API 334 Restructuring routes 335 Adding the courses partial 338 Creating the AJAX function 339 Adding an API endpoint 341 Creating an action to enroll users 344 Summary 347 Unit 7 ADDING CHAT FUNCTIONALITY 349 Lesson 30 Working with Socket.io 351 Using socket.io 352 Creating a chat box 355 Connecting the server and client 357 Summary 360 Lesson 31 Saving chat messages 361 Connecting messages to users 362 Displaying user names in chat 366 Creating a message model 369 Summary 372 Lesson 32 Adding a chat notification indicator 373 Broadcasting to all other sockets 374 Creating a chat indicator in navigation 376 Summary 378 Lesson 33 Capstone: Adding a chat feature to Confetti Cuisine 379 Installing socket.io 380 Setting up socket.io on the server 380
xiiiContentsSetting up socket.io on the client 381 Creating a Message model 384 Loading messages on connection 386 Setting up the chat icon 387 Summary 388 Unit 8 DEPLOYING AND MANAGING CODE IN PRODUCTION 389 Lesson 34 Deploying your application 391 Preparing for deployment 392 Deploying your application 394 Setting up your database in production 396 Summary 397 Lesson 35 Managing in production 398 Loading seed data 399 Linting 401 Debugging your application 404 Summary 407 Lesson 36 Testing your application 408 Basic testing with core modules 409 Testing with mocha and chai 411 Testing with a database and server 415 Summary 419 Lesson 37 Capstone: Deploying Confetti Cuisine 420 Linting and logging 421 Preparing for production 421 Deploying to Heroku 422 Setting up the database 424 Debugging in production 427 Summary 427 Appendix A JavaScript syntax introduced in ES6 429 Appendix B Logging and using Node.js global objects 436 Index 439
(This page has no text content)
ForewordI was fortunate enough to be among a crowd of about 250 folks who gathered at the first JSConf.EU conference in Berlin in late 2009, when a relatively unknown-at-the-time speaker stood up and introduced himself as Ryan Dahl. Over the next hour, he pro- ceeded to deliver a simple, no-frills talk with dry humor and little affect—not exactly the kind of talk you’d expect to receive a rousing audience response. But we all jumped to our feet and gave him a standing ovation, for multiple minutes. Why? Dahl had just changed the game for all JavaScript developers, and we knew it. He officially launched Node.js to the world. Nothing in JS would ever be the same again. In the eight or so years since, Node.js has skyrocketed to practical ubiquity, not only within the JavaScript world, but also far beyond. Node.js represents a powerful, respected, first-class, enterprise server-side platform for global-scale web applications. It sparked an explosion of interest in embedding JS in practically any computing or elec- tronic device you can imagine, from robots to television sets to light bulbs. The Node.js ecosystem is built around hundreds of thousands of published module packages in npm—the largest code repository ever for any programming language by more than 6 times. That statistic doesn’t include the countless privately installed pack- ages comprising billions of lines of JavaScript. With the enormous momentum around and attention to Node.js, it can be painfully daunting for someone who wants to learn this ecosystem to figure out where to start. I think that’s why I appreciate this book so much. From the first page, it lays out a refreshingly down-to-earth, pragmatic, clear path that shows you how to navigate your way into Node.js. You won’t find unnecessary historical or philosophical fluff here; the book jumps right into showing you how to install and configure Node.js so that you can get to the code as quickly as possible. The book is divided into short, digestible lessons. Each section is clearly organized, ensuring that you won’t get lost in the weeds and lose sight of the bigger picture.
xvi ForewordReading this book is like having Jonathan sit next to you patiently while you dig into Node.js, prompting you with enough challenges to get you to the next section review. When you’re about 50 pages into the book, you’ll look up and realize that you’ve already written a web server that responds to web requests. The feeling of having total control of your application, with no off-limits black boxes, is so empowering that you may want to give yourself a standing ovation, too! As you progress through the book’s lessons (almost 40 in total), you methodically expand the scope of your Node.js programming capabilities into API handling, data- bases, authentication, and more. This book lays out a solid checklist of what you need to learn and master to solidify Node.js as a vital tool in your programming toolbox. That’s what Node.js always has been to me, from the moment I first heard Ryan talk about it to the present. Node.js is a powerful tool that gives me, a JavaScript developer, the capability to own my entire application. I think that you’ll find this book to be the guide you’ve been looking for as you cross over from knowing about Node.js to know- ing how to wield it effectively as your favorite web application tool. Jonathan’s ready for you to begin this journey with him in Lesson 0, so what are you waiting for? Get programming with Node.js! KYLE SIMPSON, GETIFY OPEN WEB EVANGELIST
PrefaceNearly a quarter century after the internet became a public-facing tool for the world to use, the tech job market has never been larger. From new startups to large corporations, nearly all entities are looking for an online presence or, even better, sophisticated tools to push their brand and products. Luckily, you don’t need a computer-science degree or a master’s degree in data science to meet the needs of the market these days. Moreover, most of the skills you need to build these tools, you can acquire at little to no cost through open-sourced technologies. During my time at The New York Code + Design Academy, instructing intensive courses on web development and building new curriculums, I recognized the strength of a full stack education. I’ve taught students with a variety of backgrounds, most of them without development experience, to realize their programming visions in as little as three months. So why not you? I wrote this book to manifest the stages of learning web development in Node.js. Each unit guides you through a core concept in web development, with instructions on how to apply code and build your own application. I present the building blocks of a web server and show you how to piece together the components that your favorite web applications use. Using the same boot-camp learning strategy, I walk you through the development of a web application with dynamic web pages, user accounts, a database, and a live chat feature. By the end of the book, you’ll have a fully functioning applica- tion published on the internet. The work you produce from this book could spark ideas for a new application, become the start of a product for your business, or showcase your development skills as a personal portfolio piece. However you choose to use this book, you can find everything here that you need to get programming with Node.js. My goal is to make the learning process less intimidating and more exciting. The frus- tration that many new engineers feel is twofold: resources are scattered, and they don’t always deliver the complete picture. Node.js is a relatively new platform for develop- ment, and although the online community can answer common questions, new web xvii
xviii Prefacedevelopers may struggle to find full ingredient lists and recipes for building a complete application from scratch. This book covers the surface aspects and a little extra. Be ambitious while tackling the exercises in this book, and be patient while understand- ing the core concepts. Ask questions where you get stuck, and communicate with other readers through the book’s forum. (They’ll be hitting the same walls as you.) With a little practice and determination, you’ll soon be demonstrating your Node.js talent to the sea of developer-hungry organizations.
Comments 0
Loading comments...
Reply to Comment
Edit Comment