Install express globally in your system, so you can use it from anywhere:
$npm install -g express
Initialize your installation:
$express myapp; cd myapp;
Modify your package.json file inside of there, and run it. Here’s a boilerplate example of it:
{ "name": "nameofyourapphere", "version": "0.0.1", "description": "", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "dependencies": { "express": "~3.3.5" }, "author": "", "license": "BSD" }
$npm install // only if you modify the boilerplate generated package.json
You can also save dependencies to your installation file. For example, if you need extra packages, specify the –save option and you will have them
$npm install less-middleware –save
Create a boilerplate using some of the express flags:
$express -s -e -c less -f cli-app
Where:
-s or –sessions adds session support
-e or –ejs adds EJS1 engine support, by default jade2 is used
-J or –jshtml adds JSHTML3 engine support, by default jade is used
-H or –hogan adds hogan.js engine support
-c or –css adds stylesheet support (e.g., LESS4 or Stylus5), by
default plain CSS is used
-f or –force forces app generation on non-empty directory
The directories created with this option are:
1. public for static assets
2. views for templates
3. routes for request handlers
Go to the directory you created with the boilerplate options, and start your app:
$ cd cli-app; npm install; # you have to install again because you have new options after boilerplating
$ node app # your server should start at this point, and you should see the Welcome to Express page
Deploy to heroku
Your root directory needs a Procfile file (no extension), with the following line:
web: node app.js
That will tell Heroku what to run (app.js)
Also, if you are using mongodb, you need to have the following line in your app.js, so Heroku switch to the proper connection:
var host = process.env.MONGOHQ_URL || “mongodb://@127.0.0.1:27017/test”;
You also need to set MONGOHQ plugin on your heroku account. It is free for low traffic.
Also, you have to make your port Heroku friendly, and be able to switch to a known port when you are in your local env, by doing the following (in app.js as well):
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log(“Server listening on port ” + port + “.”);
});
$git init; git add .
$git commit -am “Initial commit”
$heroku create [your app name]
$git push heroku master
$heroku open
Things to keep in mind
– Variables set with “set” are global to the app now. For example:
app.set(‘appName’,’SomeGenericName’);
and later, in your template, you can read it like:
head
title= appName // Inside a jade file
– To make jsonp work, you need to set the following:
app.set(‘jsonpcallbackname’,’cb’); // So now cb=[your cb function] will be the function used for jsonp
– etags are enabled by default:
app.disable(‘etag’);