Skip to content

Conversation

@finwo
Copy link

@finwo finwo commented Jun 7, 2017

Always passing the request object to the 404 handler allows custom middleware to work when overwriting the 404 handler with a custom one.

Example use case:

// config.js

var Q = require('q');

module.exports = {
  http: {
    port        : process.env.PORT || 3000,
    default_home: [ 'index.html', 'index.htm' ],
    static_route: __dirname + '/web'
  },
  languages: {
    default: 'en',
    en: {
      "hello-world": "Hello World"
    },
    nl: {
      "hello-world": "Hallo Wereld"
    }
  },
  middleware: {
    language: function( req, res ) {
      return Q.fcall(function () {
        var requested = (req.headers[ 'accept-language' ] || '').split(',');
        requested.push(config.languages.default);
        req.language = requested
          .map(function ( language ) {
            return language.split(';').shift();
          })
          .intersect(Object.keys(config.languages))
          .shift();
      });
    }
  }
};
// app.js

// We'll use these later
var config = require('./config'),
    http   = require('http'),
    path   = require('path'),
    Router = require('node-simple-router'),
    Q      = require('q');

// Initialize router
var router = new Router( config.http );

// Register routes here

// Replace 404 handler
// Adds support for /<language>/404.html files
router.__404 = router._404;
router._404  = function( req, res, route ) {
  var filename = path.join( config.http.static_route, req.language, '404.html' );
  fs.readFile( filename, function( err, data ) {
    if ( err ) return router.__404( req, res, route );
    res.writeHead(404, {
      'Content-Type': 'text/html'
    });
    res.end( data );
  });
}

// Create server
var server = http.createServer(Q.async(function*(req, res) {
  var key, keys = Object.keys( config.middleware );
  while( key = keys.shift() ) {
    yield config.middleware[key]( req, res );
  }
  return router( req, res );
});

// Listen & notify stdout
server.listen(config.http.port);
console.log('Server running on port', config.http.port);

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant