Skip to content

Instantly share code, notes, and snippets.

@Silfen
Created May 17, 2013 10:14
Show Gist options
  • Save Silfen/5598239 to your computer and use it in GitHub Desktop.
Save Silfen/5598239 to your computer and use it in GitHub Desktop.
Express reminder

Init

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

app.listen(process.env.PORT || 8080);

Asset management (img, css, ...)

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

Routes

app.get('/', function(req, res) {
  console.log(req.query); // _GET {}
});
app.get('/:param1', function(req, res) {
	console.log(req.params); // {param1: ""}
});
app.get(/^(.*)$/, function(req, res) {
	console.log(req.params); // []
});

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

TPL

app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'twig');

    // This section is optional and can be used to configure twig.
    app.set('twig options', { 
        strict_variables: false
    });

	// Twig cache
    Twig.cache(false);
});

Render

app.get('/', function(req, res) {
	res.render('index', {
		param1: 'data'
	});
});

404 & 500

app.use(function(req, res) {
	res.status(404);
	res.render('404', {
		title: "404 - Page Not Found"
	});
});
app.use(function(error, req, res, next) {
	res.status(500);
	res.render('500', {
		title: "500 - Internal Server Error",
		error: error
	});
});

Dev & Prod

app.configure('development', function() {
	 app.use(express.errorHandler({
	 	dumpExceptions: true, // Show Throw
	 	showStack: true // Show file & line bug
	 }));
});

app.configure('production', function() {
	app.use(express.errorHandler());
});

Windows set env

set NODE_ENV=production

Linux set env

exec sudo -u some-user NODE_ENV=production

Start on process port

app.listen(process.env.PORT || 8080);

Module

// app.js
var myModule = require('./myModule.js');
console.log(myModule.test()); // 'test 01'

// myModule.js
export.test = function() {
	return 'test 01'
}

Module export Class

export = function MaClass() {
	// TODO
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment