Node.js for Beginners

Book description

Build your first production-grade web app from scratch using Node.js, Express, MongoDB, authentication, and testing with guidance from a member of the Express Technical Committee as well as a Node.js core collaborator and releaser

Key Features

  • Learn JavaScript, async programming, and event-driven architectures in Node.js
  • Discover best practices for secure deployment and testing of Node.js apps
  • Build a feature-rich web app from scratch using MongoDB, Express.js, and passport.js, including testing
  • Purchase of the print or Kindle book includes a free PDF eBook

Book Description

Node.js revolutionizes server-side JavaScript development and empowers developers to build efficient, scalable, and versatile applications across a range of use cases. This book is written by a Node.js core collaborator and releaser and is the only book for beginners on Node.js. It takes you on a progressive learning path that will give you the skills needed to leverage Node.js.

You’ll learn Node.js fundamentals and refresh your knowledge of JavaScript before transitioning to the development of modern web applications using Node.js, Express.js, and MongoDB. You’ll get hands-on with complex topics such as asynchronous programming, npm libraries, event-driven patterns for HTTP servers, RESTful API, and JSON Web Tokens. The final chapters will walk you through the deployment process, offering insights into various strategies, including bare metal setups, virtual machines, and containerization with Docker. You’ll also be guided through the use of Process Manager 2 (PM2) for efficient process management.

By the end of this Node.js book, you'll have the skills to craft, test, and deploy Node.js web applications confidently and use this powerful stack in your day-to-day projects.

What you will learn

  • Build solid and secure Node.js applications from scratch
  • Discover how to consume and publish npm packages effectively
  • Master patterns for refactoring and evolving your applications over time
  • Gain a deep understanding of essential web development principles, including HTTP, RESTful API design, JWT, authentication, authorization, and error handling
  • Implement robust testing strategies to enhance the quality and reliability of your applications
  • Deploy your Node.js applications to production environments using Docker and PM2

Who this book is for

This book is for developers eager to learn Node.js swiftly and utilize it for web app development. Front-end developers looking to delve into back-end development or become full-stack developers using Node.js will also benefit from this book’s comprehensive coverage of topics. Before you get started with this book, you’ll need to be familiar with the basics of coding (JavaScript programming or another language), Git and/or GitHub, and front-end development, as these topics aren’t covered in the book.

Table of contents

  1. Node.js for Beginners
  2. Contributors
  3. About the author
  4. About the reviewers
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Code in Action
    6. Conventions used
    7. Get in touch
    8. Share your thoughts
    9. Download a free PDF copy of this book
  6. Part 1: Node.js Overview and JavaScript Language
  7. Chapter 1: Introduction to Node.js
    1. Technical requirements
    2. Why is Node.js so popular?
      1. Lightweight and fast
      2. Cross-platform and multi-purpose
      3. Easy learning curve
      4. Ecosystem
      5. Community-powered
    3. The Node.js single-thread architecture
      1. I/O needs to be done differently
      2. Non-blocking I/O
      3. Going deeper into the event loop
    4. Node.js versions
      1. Semantic versioning (SemVer)
      2. Release details
      3. Release schedule
    5. Summary
    6. Further reading
  8. Chapter 2: Setting Up the Development Environment
    1. Technical requirements
    2. Installing Node.js on macOS, Windows, and Linux
      1. macOS
      2. Windows
      3. Linux
      4. Other environments
      5. Verifying the installation
    3. Managing Node.js versions
    4. Managing Node.js by using nvm
      1. Installing and using versions
      2. Using a .nvmrc file
      3. Node.js REPL
    5. Interacting with JavaScript using Chrome DevTools
      1. The Console panel
      2. The Network panel
      3. Using Chrome DevTools
    6. Summary
    7. Further reading
  9. Chapter 3: JavaScript Fundamentals
    1. Technical requirements
    2. JavaScript is a powerful language
    3. Understanding versioning – TC39
      1. Understanding versioning – ECMAScript
      2. What is included in the next version of JavaScript?
      3. What is not included in the JavaScript specification?
    4. Exploring JavaScript documentation
    5. Linting JavaScript code
    6. Commenting JavaScript code
      1. Using JSDoc
    7. Printing values and debugging
    8. Variables and constants
      1. Naming conventions
      2. let versus const
    9. Understanding data types
      1. undefined
      2. object
      3. boolean
      4. number
      5. string
      6. function
      7. bigint
      8. symbol
    10. Exploring numbers
      1. Arithmetic operators
      2. Assignment operators
      3. Useful methods
      4. The Math object
      5. Other numbers
    11. Exploring Dates object
    12. Conditional statements
      1. Math comparison operators
      2. Equality operators
      3. Logical operators
      4. The NOT operator (!)
      5. Equality in JavaScript
      6. The nullish coalescing operator (??)
      7. The if statement
      8. The switch statement
      9. Ternary operator
    13. Understanding loops
      1. while
      2. do...while
      3. for
    14. Using strings in JavaScript
      1. Important methods
    15. Exploring arrays
      1. Basic operations
      2. Iterating over an array
      3. Destructuring
      4. Sets
    16. Using objects in JavaScript
      1. Basic operations
      2. Iteration
      3. Shallow copy versus deep copy
      4. Merging objects
      5. Destructuring
      6. Optional chaining (?.)
    17. Exploring functions
      1. The basics
      2. Arrow functions
      3. Closures
    18. Creating and managing classes
      1. Creating a class
      2. Class methods
      3. Extending classes
      4. Static methods
      5. Getters and setters
    19. Summary
    20. Further reading
  10. Chapter 4: Asynchronous Programming
    1. Technical requirements
    2. Asynchronous programming in JavaScript
      1. The asynchronous mindset
    3. Understanding callbacks
      1. Timers and intervals
      2. Error first callbacks
      3. Callback hell
    4. Mastering promises
      1. Using promises
      2. Creating promises
      3. Callback hell with promises
      4. Parallel promises
      5. Error handling
      6. Chaining promises
    5. Using async and await to handle asynchronous code
      1. async
      2. await
      3. IIFEs
    6. Summary
    7. Further reading
  11. Part 2: Node.js Ecosystem and Architecture
  12. Chapter 5: Node.js Core Libraries
    1. Technical requirements
    2. Modularizing your code (ESM versus CJS)
      1. CommonJS (CJS)
      2. ECMAScript Modules (ESM)
      3. Understanding how interoperability works
    3. Structuring core libraries
      1. The library structure
      2. Stability index
      3. Other core libraries
      4. Command-line options
    4. Summary
    5. Further reading
  13. Chapter 6: External Modules and npm
    1. Technical requirements
    2. Managing the application with package.json
    3. Choosing the correct dependencies for your project
      1. Risks
      2. Good criteria
    4. Installing dependencies
      1. Locally or globally
      2. Dependency or development dependency
      3. Adding new dependency
      4. Installing all the dependencies
    5. Removing dependencies
    6. Understanding the package-lock.json
    7. Managing dependencies versions
      1. Outdated dependencies
    8. Building Isomorphic JavaScript
    9. Using npm scripts
    10. Executing packages directly with NPX
    11. npm alternatives
      1. Yarn
      2. PNPM
      3. Verdaccio
    12. Publishing your first package
      1. Registries
      2. npm account
      3. Prepare the package
      4. Reviewing the package
      5. Publish the package
      6. Avoid the scoped packages
      7. Release new versions
      8. Prevent accidental publishing
      9. Best practices
    13. Summary
    14. Further reading
  14. Chapter 7: Event-Driven Architecture
    1. Technical requirements
    2. Introducing events
    3. Watching for file changes
    4. The Node.js event emitter library
      1. Preventing chaos by organizing the listeners
      2. Removing listeners when they are not needed
    5. Your first HTTP server
    6. Adding an event layer to your modules
    7. Summary
    8. Further reading
  15. Chapter 8: Testing in Node.js
    1. Technical requirements
    2. Why is testing important?
      1. Testing is a complex culture
      2. Testing has to be a team activity
      3. Take advantage now
    3. Testing approach and philosophy
      1. Testing is wildly used in the world
      2. The test pyramid
    4. How should I test my code?
      1. Frameworks and libraries
      2. Our first test
      3. Testing principles and goals
    5. Writing our first test suite
      1. Utils module
      2. Test core library
      3. Using the Jest library
    6. Mastering code coverage tooling
      1. Configuration
      2. Running the tests
      3. Node.js report
    7. TDD in action
    8. Summary
    9. Further reading
  16. Part 3: Web Application Fundamentals
  17. Chapter 9: Handling HTTP and REST APIs
    1. Technical requirements
    2. How the internet works under the hood
      1. History of the internet
      2. Internet Infrastructure
      3. Request for Comments (RFC)
    3. HTTP – server and client relationship
      1. Request and response
      2. Server-side rendering
      3. Single-Page Applications (SPAs)
    4. Mastering HTTP
      1. HTTP headers
      2. Status codes
      3. Request methods
      4. HTTP payloads
      5. HTTP versions
    5. Using URLs in web applications
    6. REST APIs in a nutshell
    7. Exploring the JSON specification
    8. Debugging HTTP requests
    9. Summary
    10. Further reading
  18. Chapter 10: Building Web Applications with Express
    1. Technical requirements
    2. Getting familiar with the Express library
      1. Installing Express
      2. Hello World
      3. Using the generator
      4. Debugging
    3. Understanding template engines
      1. Choosing a template engine
      2. Rendering a template
      3. Understanding the process
    4. Mastering requests
      1. HTTP methods
      2. Routes
      3. Handlers
    5. Mastering responses
      1. Header management
      2. Status codes
      3. Redirects
      4. Sending data
      5. Sending files
    6. Using the middleware pattern
      1. Understanding the scope
      2. Middleware anatomy
      3. Adding middleware to the application
      4. Adding middleware to a route
      5. Common middleware used in Express
    7. Using third-party middleware
    8. Summary
    9. Further reading
  19. Part 4: Building Solid Web Applications with Node.js
  20. Chapter 11: Building a Web Application Project from Scratch
    1. Technical requirements
    2. The project Kickoff
      1. The project goal
      2. Starting with the first step
    3. Building a REST API
      1. Adding the routes
      2. Adding the stores
      3. Adding the static files
      4. Adding the templates
    4. Testing with supertest
      1. Adding stores to the server
      2. Creating test utils
      3. Adding server tests
    5. Reviewing the final result of the project
      1. The about page
      2. Let’s celebrate it!
      3. Next steps
    6. Summary
  21. Chapter 12: Data Persistence with MongoDB
    1. Technical requirements
    2. What is MongoDB?
      1. Versions
    3. Setting up MongoDB
      1. Installing Docker
      2. Running MongoDB with a container
      3. Running MongoDB with Docker Compose
      4. Adding Docker commands to package.json
      5. Connecting to MongoDB
      6. Other ways to install MongoDB
    4. How to load secrets in Node.js
      1. Environment variables
      2. The .env file
      3. dotenv
    5. Using an ORM – Mongoose
    6. Migrating a web application to MongoDB
      1. Installing dependencies
      2. Managing the secrets
      3. Migrating the data layer
    7. Testing our MongoDB integration layer
      1. Update the utilities
      2. Refactoring the test suite
      3. Some tests must change
      4. Checking the coverage
    8. Summary
    9. Further reading
  22. Chapter 13: User Authentication and Authorization with Passport.js
    1. Technical requirements
    2. Understanding modern authentication and authorization
      1. Authentication
      2. Authorization
    3. JWT in a nutshell
      1. The process
      2. The theory
      3. Cryptography 101
      4. JWT structure
      5. JWT.io
    4. Understanding Passport.js fundamentals
    5. Adding authentication and authorization to our web application
      1. Clone the base project
      2. Setup
      3. Run the tests
      4. The UI changes
      5. Added dependencies
      6. Changes in the frontend
      7. Added a new store for users
      8. JWT utilities
      9. Adding new routes
      10. Improved testing utilities
      11. Test case changes
      12. Test coverage
    6. Summary
    7. Further reading
  23. Chapter 14: Error Handling in Node.js
    1. Technical requirements
    2. Exploring the types of errors
      1. Syntax errors
      2. Runtime errors
    3. Throwing meaningful errors
      1. The error object
      2. Custom errors
    4. Managing errors in Express
      1. Error-handling middleware
      2. Custom errors
    5. Gracefully shutting down the application
      1. Events
      2. Exit codes
      3. Avoiding zombie processes
    6. Summary
    7. Further reading
  24. Chapter 15: Securing Web Applications
    1. Technical requirements
    2. The importance of security
      1. Social engineering
      2. Risks in the supply chain
      3. The business impact
    3. Where to start with security
      1. OWASP Top 10 overview
      2. CWE
      3. CVE
      4. Node.js threat model
      5. The Node.js official recommendations
    4. Improving the security of our applications
      1. Put it into practice
    5. Becoming an ethical hacker
      1. Coordinated vulnerability disclosure (CVD)
      2. Bounty programs
      3. Getting the skills
    6. Summary
    7. Further reading
  25. Part 5: Mastering Node.js Deployment and Portability
  26. Chapter 16: Deploying Node.js Applications
    1. Technical requirements
    2. Defining the requirements
    3. Using a GitHub repository
      1. Creating a GitHub repository
      2. Pushing the code to the repository
    4. Continuous integration with GitHub Actions
    5. Using MongoDB Atlas
    6. Deploying Node.js applications with PM2
      1. Creating a DigitalOcean Droplet
      2. Connecting to the machine
      3. Preparing the machine
      4. Cloning the repository
      5. Installing the dependencies
      6. Preparing the environment
      7. Managing the application with PM2
      8. Accessing the application
    7. Summary
    8. Further reading
  27. Chapter 17: Dockerizing a Node.js Application
    1. Technical requirements
    2. Containers and cloud-native solutions with Docker
      1. Docker lifecycle
      2. Dockerizing the application
      3. Managing the application with Docker
      4. Adding docker build to the CI
      5. Pushing the image to Docker Hub
      6. Publishing the image with GitHub Actions
    3. Running the containers
    4. Using Cloudflare
    5. Next level – Twelve-Factor App principles
    6. Cleaning up
    7. Summary
    8. Further reading
  28. Index
    1. Why subscribe?
  29. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share your thoughts
    3. Download a free PDF copy of this book

Product information

  • Title: Node.js for Beginners
  • Author(s): Ulises Gascón
  • Release date: May 2024
  • Publisher(s): Packt Publishing
  • ISBN: 9781803245171