Table of Contents for
Node.js 8 the Right Way

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Node.js 8 the Right Way by Jim Wilson Published by Pragmatic Bookshelf, 2018
  1. Title Page
  2. Node.js 8 the Right Way
  3. Node.js 8 the Right Way
  4. Node.js 8 the Right Way
  5. Node.js 8 the Right Way
  6.  Acknowledgments
  7.  Preface
  8. Why Node.js the Right Way?
  9. What’s in This Book
  10. What This Book Is Not
  11. Code Examples and Conventions
  12. Online Resources
  13. Part I. Getting Up to Speed on Node.js 8
  14. 1. Getting Started
  15. Thinking Beyond the web
  16. Node.js’s Niche
  17. How Node.js Applications Work
  18. Aspects of Node.js Development
  19. Installing Node.js
  20. 2. Wrangling the File System
  21. Programming for the Node.js Event Loop
  22. Spawning a Child Process
  23. Capturing Data from an EventEmitter
  24. Reading and Writing Files Asynchronously
  25. The Two Phases of a Node.js Program
  26. Wrapping Up
  27. 3. Networking with Sockets
  28. Listening for Socket Connections
  29. Implementing a Messaging Protocol
  30. Creating Socket Client Connections
  31. Testing Network Application Functionality
  32. Extending Core Classes in Custom Modules
  33. Developing Unit Tests with Mocha
  34. Wrapping Up
  35. 4. Connecting Robust Microservices
  36. Installing ØMQ
  37. Publishing and Subscribing to Messages
  38. Responding to Requests
  39. Routing and Dealing Messages
  40. Clustering Node.js Processes
  41. Pushing and Pulling Messages
  42. Wrapping Up
  43. Node.js 8 the Right Way
  44. Part II. Working with Data
  45. 5. Transforming Data and Testing Continuously
  46. Procuring External Data
  47. Behavior-Driven Development with Mocha and Chai
  48. Extracting Data from XML with Cheerio
  49. Processing Data Files Sequentially
  50. Debugging Tests with Chrome DevTools
  51. Wrapping Up
  52. 6. Commanding Databases
  53. Introducing Elasticsearch
  54. Creating a Command-Line Program in Node.js with Commander
  55. Using request to Fetch JSON over HTTP
  56. Shaping JSON with jq
  57. Inserting Elasticsearch Documents in Bulk
  58. Implementing an Elasticsearch Query Command
  59. Wrapping Up
  60. Node.js 8 the Right Way
  61. Part III. Creating an Application from the Ground Up
  62. 7. Developing RESTful Web Services
  63. Advantages of Express
  64. Serving APIs with Express
  65. Writing Modular Express Services
  66. Keeping Services Running with nodemon
  67. Adding Search APIs
  68. Simplifying Code Flows with Promises
  69. Manipulating Documents RESTfully
  70. Emulating Synchronous Style with async and await
  71. Providing an Async Handler Function to Express
  72. Wrapping Up
  73. 8. Creating a Beautiful User Experience
  74. Getting Started with webpack
  75. Generating Your First webpack Bundle
  76. Sprucing Up Your UI with Bootstrap
  77. Bringing in Bootstrap JavaScript and jQuery
  78. Transpiling with TypeScript
  79. Templating HTML with Handlebars
  80. Implementing hashChange Navigation
  81. Listing Objects in a View
  82. Saving Data with a Form
  83. Wrapping Up
  84. 9. Fortifying Your Application
  85. Setting Up the Initial Project
  86. Managing User Sessions in Express
  87. Adding Authentication UI Elements
  88. Setting Up Passport
  89. Authenticating with Facebook, Twitter, and Google
  90. Composing an Express Router
  91. Bringing in the Book Bundle UI
  92. Serving in Production
  93. Wrapping Up
  94. Node.js 8 the Right Way
  95. 10. BONUS: Developing Flows with Node-RED
  96. Setting Up Node-RED
  97. Securing Node-RED
  98. Developing a Node-RED Flow
  99. Creating HTTP APIs with Node-RED
  100. Handling Errors in Node-RED Flows
  101. Wrapping Up
  102. A1. Setting Up Angular
  103. A2. Setting Up React
  104. Node.js 8 the Right Way

Setting Up the Initial Project

Rather than write everything from scratch, you’ll want to rely more on the code download that accompanies this book than in previous chapters. In the fortify directory, you’ll find three subdirectories:

  • b4-initial—You should copy this directory to a local directory called b4.

  • b4—This represents the project as it should be at the end of the chapter. No peeking!

  • b4-final—This includes everything in b4 plus more functionality—the ability to add books to bundles, book title autocomplete, etc.

The b4-initial project that you’ll be building on combines the Express framework and the webpack compilation of the last two chapters. Here’s a file listing of that directory:

 $ ​​tree​​ ​​-F​​ ​​--dirsfirst​​ ​​b4-initial/
 b4-initial/
 ├── app/
 │   ├── index.ts
 │   └── templates.ts
 ├── development.config.json
 ├── package.json
 ├── server.js
 ├── tsconfig.json
 └── webpack.config.js
 
 1 directory, 7 files

The app directory contains an index.ts and a templates.ts file, just like in the last chapter. These files have some minor differences from their predecessors that will make sense as you make changes during this chapter.

The tsconfig.json is identical to the last chapter’s version, and the webpack.config.js is quite similar except that it uses Node.js’s path module for OS-specific file-path manipulations.

development.config.json contains the configuration settings for running the project in development mode. It has Elasticsearch connection settings and a serviceURL string, which we’ll discuss shortly.

The package.json file describes the project, and server.js pulls it all together. We’ll dive into the server.js file in a bit.

To get started, copy the b4-initial into your own working directory called b4. Now open a terminal to your new b4 directory.

The first thing to do is run npm install to get all the dependencies.

 $ ​​npm​​ ​​install

And then you can start the server with npm start:

 $ ​​npm​​ ​​start

You can leave this running for the rest of the chapter, until we get to the part about running in production. As you make changes, nodemon will pick them up, recompile the webpack assets, and restart the server.

Next let’s dive into server.js, which is core to the work you’ll be doing in this chapter.

Reviewing the server.js File

The server.js file is the backbone that holds the project together. It pulls in all the modules and configures Express and related middleware.

Let’s take a quick peek at this important file before we start adding to it. Here it is:

1: 'use strict'​;
const​ pkg = require(​'./package.json'​);
const​ {URL} = require(​'url'​);
const​ path = require(​'path'​);
5: 
// nconf configuration.
const​ nconf = require(​'nconf'​);
nconf
.argv()
10:  .env(​'__'​)
.defaults({​'NODE_ENV'​: ​'development'​});
const​ NODE_ENV = nconf.​get​(​'NODE_ENV'​);
const​ isDev = NODE_ENV === ​'development'​;
15: nconf
.defaults({​'conf'​: path.join(__dirname, ​`​${NODE_ENV}​.config.json`​)})
.file(nconf.​get​(​'conf'​));
const​ serviceUrl = ​new​ URL(nconf.​get​(​'serviceUrl'​));
20: const​ servicePort =
serviceUrl.port || (serviceUrl.protocol === ​'https:'​ ? 443 : 80);
// Express and middleware.
const​ express = require(​'express'​);
25: const​ morgan = require(​'morgan'​);
const​ app = express();
app.use(morgan(​'dev'​));
30: 
app.​get​(​'/api/version'​, (req, res) => res.status(200).json(pkg.version));
// Serve webpack assets.
if​ (isDev) {
35: const​ webpack = require(​'webpack'​);
const​ webpackMiddleware = require(​'webpack-dev-middleware'​);
const​ webpackConfig = require(​'./webpack.config.js'​);
app.use(webpackMiddleware(webpack(webpackConfig), {
publicPath: ​'/'​,
40:  stats: {colors: ​true​},
}));
} ​else​ {
app.use(express.​static​(​'dist'​));
}
45: 
app.listen(servicePort, () => console.log(​'Ready.'​));

Much of this should look familiar to you, so I won’t go over all of it. But there are a few parts you should pay some attention to.

First, check out the part about NODE_ENV around line 13. This environment variable is widely used to indicate whether a Node.js program is running in production mode. Here we pull it from nconf, with the default set to development.

Next, on line 19, observe the serviceUrl constant. This is a URL instance implemented in the Node.js core module url and adhering to the URLinterface web standard.[86] [87] We’ll use URL instances to construct URLs relative to the main service URL throughout.

Lastly, take a look at the webpack-dev-middleware part beginning on line 34. The webpack-dev-middleware module serves webpack assets directly from memory through Express.[88] When we’re in dev mode, we’ll serve them this way, but in production mode we want to serve static files from the dist directory. This directory doesn’t yet exist, but will once you invoke npm run build, which is configured in the package.json to execute webpack.

Take a minute to familiarize yourself with this file since you’ll be building on top of it throughout the chapter. When you’re ready, there’s one more bit of setup: your localhost alias.

Configuring a localhost Alias

When developing services locally, it’s typical to rely on localhost at IP address 127.0.0.1. We’ve been doing it all along in this book.

Unfortunately, this is a problem for authentication using OAuth, which we’ll be doing later in this chapter. To be clear, nothing in OAuth specifically prohibits using localhost, but the three providers we’ll be using have mutually incompatible rules around allowable domain names for development.

Facebook’s app-configuration page allows you to use localhost for website URLs but prohibits 127.0.0.1. Twitter allows you to use 127.0.0.1 but disallows localhost. For its part, Google authentication is OK with both localhost and 127.0.0.1, but otherwise requires hostnames to end in a legitimate top-level domain (TLD).

We need a hostname that all three services will allow and that we can point to 127.0.0.1 for local development. For this, I’ve chosen b4.example.com. The .com suffix satisfies Google’s TLD requirement, and the example.com second-level domain is reserved by IANA for illustrative purposes, so it can’t create an accidental collision.

To point b4.example.com to 127.0.0.1, you need to add an entry to your operating system’s hosts file. On Mac OS X and Linux, you can find this file at /etc/hosts. On Windows, it’s at \WINDOWS\system32\drivers\etc\hosts.

Open your hosts file in a text editor (this generally requires root privileges), then add the following line:

 127.0.0.1 b4.example.com

After you have saved the file, any requests you make to b4.example.com will go to your loopback interface, IP address 127.0.0.1. Try it out by opening http://b4.example.com:60900 in a browser. It should look like the figure.

images/fortify-b4-initial.png

If so, great! Now you’re ready to start developing. Let’s start by adding support for persistent sessions.