New Express Project

Overview

The easiest way to setup a new project is to use a project generator as they create the necessary skeleton and sometimes best practices. Express has built one to help get going quick and is installed using:

npm install express-generator -g

Generate Your App

In one line, you'll create a directory and some dependencies to your package.json. Run the Express app generator and create your app directory with below:

express myapp

Once you've created the default app you'll need to install all the dependencies. Do this by executing the command npm install and now you'll see the directory "node_modules" generated in your project.

For more on what this generator provides take a look at the Express app-gen docs.

warning: If the "myapp" folder is not empty/exists, then using the express myapp command will cause an error. You may get asked if you want to override duplicates. You can say “yes” or “no” as you see fit.

Inspecting the Skeleton

The default files and directories will look like below:

.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade

7 directories, 9 files

The Package.JSON

Express generator creates the following default package.json (for in-depth explanations of package.json keys, check this):

{
  "name": "myapp",              // required field that names your app
  "version": "0.0.0",           // required field managing the version
  "private": true,              //
  "scripts": {
    "start": "node ./bin/www"   // used as npm scripts
  },
  "dependencies": {
    "body-parser": "~1.12.0",   // Node.js body parsing middleware
    "cookie-parser": "~1.3.4",  // cookie parsing with signatures
    "debug": "~2.1.1",          // tiny node.js debugging utility modelled after node core's debugging technique
    "express": "~4.12.2",       // Express
    "jade": "~1.9.2",           // whitespace-sensitive template language for writing HTML
    "morgan": "~1.5.1",         // HTTP request logger middleware
    "serve-favicon": "~2.2.0"   // middleware for serving a favicon
  }
}

There are a lot of packages in there, for now don't worry too much about them. To learn further about what each of those do you can look them up on www.npmjs.org.

Whenever you create a project (whether via a generator or npm init) the file package.json will get generated which will describe your project and more importantly help npm install your project’s dependencies. As you might expect, a project that uses Express will depend on the Express npm module.

When you install a library with npm it is installed into the project you’re working on, into a folder called node_modules. If you have two projects and install Express in one, that does not mean you will be able to use it in the other project. Each project keeps their modules isolated from each other.

note: globally installing a module is possible using the -g option, but not recommended for every case as some modules are project dependent.

The App.js

You may notice some error handlers and usage of different modules and middleware that was added by the Express project generator. For now, we'll ignore most of this as the topics relevant to them will get covered in other guides. However, the following two items are a light introduction to routes:

var routes = require('./routes/index');
var users = require('./routes/users');

Notice the folder in the project called "routes" and this topic will be covered in greater detail here, but for now know that the below defines the "home" and "users" pathes:

app.use('/', routes);
app.use('/users', users);

Configuration Scripts

In Express 4.0, all middleware has been removed so that they can be maintained and updated independently from core Express (except the static middleware), thus they need to be called separately (what you see in app.js).

The bin/ directory serves as a location where you can define your various startup scripts with appropriate configurations, the www is an example on how this should look. Ultimately you could have several startup scripts, such as: test, stop or restart. Having this structure allows you to modularize configurations without touching the app.js.

Create Hello World

The app.js expects your routes to be defined in a new directory with appropriate javascript files. To get our "Hello World" up and running we'll need to navigate to the /project-folder/routes/ where we'll find the index.js in which you'll notice something like below, except it says "Hello Express", modify this so it reflects below:

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Hello World!' });
});

This is utilizing the Jade view rendering engine to populate the information above in the views listed in the folder views creating a level of MVC encapsulation.

If you've followed the Setup guide, then launch your app this way:

nodemon ./bin/www

You should see your app in the browser at http://localhost:3000/

Image of Hello World

Well done!

Improving Your Project Environment

There are a few simple things you can do to improve your environment to start out. Lets open up the package.json again and head down to the "scripts" key. Lets replace the "start" script with the following to add auto-updating when we make changes to our project:

"scripts": {
    "start": "nodemon --exec babel-node -- --optional strict --stage 1 --  ./bin/www"
},

To execute this new script, simply run npm start in your terminal.

Later you can add more scripts to help with common tasks that might require a series of options like the above that would get tedious to retype every time you wanted to execute the action.

Next Steps

Choosing View Rendering Engines

There are a few options with regards to view rendering engines and therefore a separate guide was created to break them down. Find that guide here.

With the Express project generator you get the option of creating with these view rendering engines:

-e, --ejs           add ejs engine support (defaults to jade)
    --hbs           add handlebars engine support
-H, --hogan         add hogan.js engine support

Create Your First Test

Testing is an important part of Node.js development and there are helpful frameworks to make this simpler. Check out the testing guide to get yourself started.

Debugging

As with any programming, debugging will be a constant necessity. You'll recall that "Morgan" was added to our default project. This is one of the logger middleware packages that will help when debugging. For more on debugging, check out the complete guide here.

Guides

References

Fork me on GitHub