What does "./bin/www" do in Express 4.x?

Blaszard picture Blaszard · Apr 19, 2014 · Viewed 70.5k times · Source

I just started to learn about Express 4.0 in my Node.js app, and I found that it generated ./bin/www file, on which only the application server and port settings are written and everything others like middleware and routing is defined in ./app.js file.

However, I'm not sure what this ./bin/www does. I've used Express 3.x and I have always defined server and port settings as well as routing and middleware on the identical ./app.js file, and launched my node app with node app.js. So what's the point of using the ./bin/www? Does it only separate the server and port definition from others?

Right now, when I create the package using express-generator, the package.json includes the following definition:

"scripts": {
    "start": "node ./bin/www"
}

However, I wonder whether I should launch my app using node ./bin/www, or npm start. Which command should I run to start my app?

And also, when I deploy my app to heroku, what should I write in the Procfile file? Is web: node app.js enough?

Answer

Andy picture Andy · Apr 23, 2014

In Express 3.0, you normally would use app.configure() (or app.use()) to set up the required middleware you need. Those middleware you specified are bundled together with Express 3.0.

Example:

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.compress());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());

In Express 4.0 however, all middleware have been removed so that they can be maintained and updated independently from the 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. The www is an example to start the express app as a web server.

Ultimately, you could have different scripts like test, stop, or restart, etc. Having this structure allows you to have different startup configurations, without cramming everything into app.js.

The correct way to start your Express app is:

npm start

To deploy an Express 4.x app to Heroku, add this to your Procfile:

web: npm start

Or if you can just use the start script in your package.json, heroku will automatically uses that, read more here

"scripts": {
    "start": "node ./bin/www",
}