Express generator provides boilerplate to quickly create express server. It also provides configuration for css middleware and view engine and debugging.

Introduction

In order to quickly create a express server, you can use the express generator provided by the express itself. It creates a boilerplate code, with sample routes defined. You can quickly start using the boilderplate.

In order to install express-generator, run the command

npm install express-generator -g

Once the express-generator is installed, you can use it to create the boilerplate code anywhere. So go the the path where you want to create the server, and run the command

express server

Setting the view engine

This will create a project containing express and its dependencies inside a folder named server. By default it will use the view engine as jade.

You can set the view engine to ejs,hbs,hjs,jade,pug, twig and vash. Use the following command to set the view engine

express --view=ejs server

This will set the view engine to ejs, and also create ejs templates inside views folder.

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

If you have already created the server, and want to change the templating engine, then you need to install ejs first.

npm install ejs --save

Or you can choose to not use any view engine at all. This is particularly helpful when you are using express to create a api server, and do not want to use server side rendering.

Setting no-view will not create a views folder.

express --no-view server

Using css middleware

You have option to use sass, less, stylus and compass. It defaults to css.

In order to use sass, run the command

express --css=sass server

This will create a folder named server, and add sass middleware code inside app.js.

app.use(sassMiddleware({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true, // true = .sass and false = .scss
  sourceMap: true
}));

Debugging

Express provides debugging feature builtin inside the boilerplate. It uses a package called debug. Debug allows you to set debug only the part of application using the environment variable.

For example, if you only wish to see the logs of http-server, you can use debug as follows

/* Its not necessary to give `http-server` name. You can give
 any name you wish to give. */
var debugHttpServer = require('debug')('http-server'); 
var http = require('http');
var app = require('express')();

var server = http.createServer(app);

server.listen(8080);

server.on('error', function(e){
    debugHttpServer('Error running server', e);
});

server.on('listening',function(){
   debugHttpServer('Listening on port 8080');
});

Then you can run the server with proper environment variable

DEBUG=http-server npm start

If you had given name as "http" in debug,

var debugHttpServer = require('debug')('http');

then you should use

DEBUG=http npm start