Skip to content

Instantly share code, notes, and snippets.

@dstevensio
Created December 4, 2014 00:08
Show Gist options
  • Save dstevensio/a9286b744c105d4bfed8 to your computer and use it in GitHub Desktop.
Save dstevensio/a9286b744c105d4bfed8 to your computer and use it in GitHub Desktop.
Express vs hapi
// GETTING STARTED:
// Express
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
// hapi
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.route({
path: '/',
method: 'GET',
handler: function (request, reply) {
reply('hello world');
}
});
server.start(function (err) {
// server running on port 3000
});
// MIDDLEWARE CONCEPT
// express
// before app.listen
app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
})
// hapi
// before server.start
server.register({
register: require('./path/to/plugin')
}, function (err) {
if (err) console.error(err); // Plugin failed to load
});
// plugin file
exports.register = function (server, options, next) {
console.log('Time: %d', Date.now());
next();
};
exports.register.attributes = {
name: 'basicExample',
version: '1.0.0'
};
@hasdavidc
Copy link

hi shakefon - you sent this gist from IRC about a week ago to help me pick up hapi. (thanks again for that!)

I think your Hapi middleware analog should use plugin.ext('onRequest', function(request, next) {}) instead of just the console.log (which would only run initially upon server start, as opposed to for every request as middleware sorta implies).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment