Appendix B. Technical Preconditions and Requirements

This appendix explains some basic concepts around Node and adds extra material that supplements the book’s content.

On ES6/ES2015

You’ll notice that we are using ES5 syntax as a base for the code throughout this book. The simple reason is that we wanted to use the more common syntax to ensure that everyone is able to comfortably read through this book.

We highly encourage you to try out ES6 by using compilers/transpilers such as Babel. Node is slowly adopting ES6—in the meantime, you can prepare your application and ensure that you are ready to deploy to production when ES6 is fully supported.

Setting Up Your Node.js Environment

This book assumes a working Node.js environment and the ability to install various modules using npm. This section runs through setting up Node in order to ensure that you will be able to follow the book.

First, install Node by either downloading and running the installer from nodejs.org’s Downloads section or leveraging a package manager such as brew, pacman, or apt-get. Verify that the installation worked by typing which node or node -v into your terminal—this should display either the path to your node executable or your local node version.

Note

The download from nodejs.org always serves the most recent stable version of Node and should be favored over alternative ways of installing Node whenever possible.

Once Node is set up, you can proceed with installing Express by utilizing npm. To see if your environment is working correctly, simply enter npm in your terminal. You should see a brief explanation about using the command.

Managing Node Versions or Alternative Installations

By using the installer obtained from nodejs.org, the newest stable version of Node.js will be installed on your machine. Sometimes you might have to use another version of Node or even switch between multiple versions based on the project you are working on. nvm (which stands for Node Version Manager) is a community project that allows for doing exactly this.

You can use the install script for cURL by running the following command:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash

Assuming you’d like to install version 5.7.0 of Node.js (the latest stable version of Node), you’d run the following command:

nvm install 5.7.0

Once the installation is done, run nvm use 5.7.0 and your environment is set up: 5.7.0 will be your system’s default Node.js version.

Should you be required to run multiple versions of Node, you have the choice of running the specific version either by using the command-line interface nvm run 5.7.0 or by setting up a project-specific .nvmrc file containing the target version number.

Installing the Express Generator

Assuming the setup works as intended, you can proceed by installing and using the Express generator. This generator allows for scaffolding your project and creating a reasonable structure:

npm install -g express-generator

You will notice that we use the -g option. This implies that we want to install the generator globally and not just as a module for our current project.

To verify that the Express generator was set up correctly, type the following command to see the generator’s usage information:

express --help

You can find more documentation on the generator and Express on ExpressJS.com.

Setting Up Express

If you’d like to avoid using a generator to set up your first Express project, you can start by following these instructions:

  1. Create a new folder with mkdir projectname.

  2. Navigate to the folder by running cd projectname.

  3. Create a package.json file by running npm init in your project’s root folder. Don’t worry about fleshing out the content yet—the next section will go into package.json in more detail.

  4. Run touch app.js (or whatever name you defined in step 3) to create your application’s entry point. Here you’ll define many of the modules your project ends up using, create the server itself, and initialize the middleware your project might rely on (see Chapter 4).

  5. Finally, run npm install express --save to install the most important module for your project: Express itself.

After you’ve taken care of these five steps you’re ready to implement a basic Express application that you can then build out in order to achieve additional functionality:

var app = require('express')();

app.get('/', function(req, res) {
  res.send('Hello from Express!');
});

app.listen(3000, function() {
  console.log('App active on port 3000');
});

The preceding example presents the beauty of Express: with a mere nine lines of code, you can run a simple web server. By navigating to localhost:3000, you’ll be presented with a hearty Hello from Express!.

Run the application with the following command: node app.js. Congratulations!

You can extend this by starting to serve static resources (such as your site’s CSS and JavaScript or images) by modifying the preceding example:

var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('/', function(req, res) {
  res.send('Hello from Express!');
});

app.listen(3000, function() {
  console.log('App active on port 3000');
});

You can also specify that static resources are served through another folder structure such as /resources by using the following method:

app.use('/resources', express.static('public'));

It is safer to declare the folder by using the absolute path to the folder: __dirname + '/public'. express.static uses relative paths—this leads to issues when running the Node process from another folder:

app.use('/static', express.static(__dirname + '/public'));

Creating and Maintaining Your package.json File

If you’ve been using the Express generator, you will notice that a file called package.json was generated for you. Otherwise, go ahead and create one by running npm init in your terminal.

package.json contains information about module dependencies, the project’s authors, versioning, and a section called scripts containing commands for npm. In the following example case, running npm start or npm run start starts a new instance of your newly generated Node server:

{
  "name": "book",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0"
  }
}

You can also extend the scripts section for other tasks, like running eslint:

"scripts": {
  "start": "node ./bin/www",
  "lint": "eslint app.js lib/** routes/**"
},
...

Damon Bauer wrote a great blog post on using npm scripts for a variety of tasks that normally would be covered through task runners like grunt, gulp, or broccoli.1 It’s a highly recommended read in case you are looking for further inspiration.

By running npm install, all entries in the dependencies section will be retrieved. npm update --save ensures that your project uses the latest version of each dependency in the dependencies section and updates package.json accordingly. The site http://www.npmjs.com allows you to search for modules or browse popular choices—you will notice that npm itself is a module that can be updated using npm.

Additional sections—such as bugs—can be defined to help developers understand how to interact best with the project, how to contact the developers in case they want to get in touch, or under which license the project was published. Check out http://browsenpm.org/package.json for an interactive overview about all possible package.json sections.

Application Configuration

Environment variables are a sensible way of handling configuration details, such as database passwords or third-party API credentials, without hardcoding them in your application’s code. The Twelve-Factor App methodology defines this as separation of code and configuration and sees the benefit of being able to quickly change between different deployment targets such as production environments.

The module dotenv was designed to specifically cater to this use case and utilizes a configuration file called .env (located in your project’s root folder) that stores information in the NAME=VALUE format:

MONGO_DB=mongodb://localhost/database
MONGO_USER=tim
MONGO_PW=sloths-are-more-awesome-than-monkeys

You can access these details by loading the module and calling the config method. You will notice that process.env is going to be populated with the information from your .env file:

require('dotenv').config();

var mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_DB);

dotenv allows you to pass configuration options, such as path (in case you require a different location for your configuration file), silent (which suppresses warnings when no .env file can be found), or encoding (the default is utf8).

Version Control and Configuration Files

Make sure to exclude your dotenv configuration files by adding them to your project’s .gitignore file. Please also check out the dotenv FAQ for more information on this matter.2

Working with JSON/URL-Encoded Bodies in Express

As of Express 4.0, working with JSON- and URL-encoded bodies has changed slightly, and requires an additional setup step to be able to work with that data when it is POSTed to your server. The body-parser npm module, when used in the following format, will allow your server to support those entities:

var bodyParser = require('body-parser')
var app = require('express')();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset