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

Serving in Production

When you’re actively developing your Node.js code, you want the turn-around time to be fast and its reliance on external systems to be low. So far we’ve been keeping things this way, using the isDev variable to occasionally make choices about whether to do things the development way.

In this section, you’ll take the remaining steps to prepare the application to run in production mode. Once everything is in place, we’ll clean out the project and reinstall the dependency modules to perform a clean production test run.

The first thing we need to switch out is how session data is stored. In a production environment, you’re usually better off storing sessions on a service like Redis than on the filesystem.

Redis is a fast, open source, in-memory key/value store.[103] You can use it as a database, cache, or message broker, and you can control when and if it synchronizes to disk.

We’re going to use Redis to store session information when NODE_ENV is set to production. To do this, you’ll need to install Redis, then install the Redis session module, add a production.config.json file, and wire it up in your server.js file. Let’s get started.

Installing Redis

The first step to using Redis to store session info is to install the Redis service. This varies by platform, but the Redis Download page has binaries for most popular operating systems.[104] If you’re using Ubuntu, you can install the Redis server and command-line utilities from the repositories using apt:

 $ ​​sudo​​ ​​apt​​ ​​install​​ ​​redis-server​​ ​​redis-tools

On Mac OS X with homebrew, it’s even easier:

 $ ​​brew​​ ​​install​​ ​​redis

Although the Redis project does not itself distribute a Windows build, you can get one from the Microsoft Open Tech group on GitHub.[105]

Once you’ve installed Redis, you can test if it’s working with the redis-cli command-line program.

 $ ​​redis-cli
 127.0.0.1:6379>​​ ​​ping
 PONG
 127.0.0.1:6379>​​ ​​quit

If you see this, great! You’re ready to create a production config to point to it. Start by copying your development.config.json to production.config.json. Ideally, at this point you’d switch over all the configuration settings to more permanent production values. But for now, all we need to do is add the Redis configuration values.

Open your brand-new production.config.json file for editing, and add a section for Redis like so:

 "redis"​: {
 "host"​: ​"localhost"​,
 "port"​: 6379,
 "secret"​: ​"<your Redis secret here>"
 }

To connect to Redis, your server needs to know where to find it (the host and port). The default TCP port that Redis uses is 6379. The secret is used in the same way the FileStore used it earlier in the chapter—to sign cookies. If you ever need to simultaneously sign all users out of the system, changing the secret will do it! Once you save the production.config.json file, you’re ready to wire it up to your server.

Wiring Up Redis to Express

At this point you have Redis installed and a production.config.json that contains settings for it. Now you’re ready to install the connect-redis module and use it for session storage. Use npm to install it.

 $ ​​npm​​ ​​install​​ ​​--save​​ ​​-E​​ ​​connect-redis@3.3.2

Next, open your server.js file for editing and find the comment that reads, “Use RedisStore in production mode.” Add the following code there.

 // Use RedisStore in production mode.
 const​ RedisStore = require(​'connect-redis'​)(expressSession);
 app.use(expressSession({
  resave: ​false​,
  saveUninitialized: ​false​,
  secret: nconf.​get​(​'redis:secret'​),
  store: ​new​ RedisStore({
  host: nconf.​get​(​'redis:host'​),
  port: nconf.​get​(​'redis:port'​),
  }),
 }));

This code should look familiar to you based on its similarity to setting up the FileStore class for storage. First we pull in the RedisStore class attached to the expressSession object. From there, we call app.use, passing in the expressSession middleware with its matching configuration.

This time, we set saveUninitialized to false. We don’t want to store uninitialized sessions in production mode—we’d rather wait until the user authenticates to bother saving session information. And rather than hard-coding the secret, we pull it in through nconf.

For the store, we pass in a new instance of RedisStore, configured with settings from nconf. The connect-redis module supports additional options,[106] but these are all we need for this application.

Save your server.js file. All of the code is in place to run in production mode now except the dist directory assets. It’s time to do an end-to-end test of production mode.

Running in Production Mode

At this point, all of the code is in place to run in production mode. It’s time to tell webpack to build the assets.

Head to a terminal and invoke npm run build.

 $ ​​npm​​ ​​run​​ ​​build

You can confirm that it worked by taking a peek at the dist directory.

 $ ​​tree​​ ​​-F​​ ​​./dist
 dist
 ├── 674f50d287a8c48dc19ba404d20fe713.eot
 ├── 89889688147bd7575d6327160d64e760.svg
 ├── 912ec66d7572ff821749319396470bde.svg
 ├── b06871f281fee6b241d60582ae9369b9.ttf
 ├── bundle.js
 └── index.html
 
 0 directories, 6 files

Now we’re ready to try a production run.

To make sure everything is working according to plan, the safest thing is to remove and reinstall all of the dependency modules in production mode. That way you don’t accidentally depend on something that you forgot to save to your package.json file.

Start by removing the contents of the node_modules. Be careful not to delete something else by accident!

 $ ​​rm​​ ​​-rf​​ ​​node_modules

Now run npm install but with NODE_ENV set to production. This will prevent npm from installing any devDependencies.

 $ ​​NODE_ENV=production​​ ​​npm​​ ​​install

And finally, start up the server in production mode.

 $ ​​NODE_ENV=production​​ ​​npm​​ ​​start
 
 > b4@1.0.0 start ./code/fortify/b4
 > nodemon --ignore './sessions' server.js
 
 [nodemon] 1.12.1
 [nodemon] to restart at any time, enter `rs`
 [nodemon] watching: *.*
 [nodemon] starting `node server.js`
 Ready.

All that’s left is to try it out! Open http://b4.exampl.com:60900/ in a browser and see if it all works. You should be able to sign in, add bundles, and sign out. Woo! Let’s recap where we went in this chapter.