requiring file inside request

I am playing around with Node.js and I was wondering if what I'm doing can be considered best practice or not, I still got a lot of stuff to learn.

I am trying to implement a multi-language layout, by creating more JSON files that are then loaded depending on the http header (language). What I am doing is this:

exports.index = function(req, res){
try {
    var words = require('../languages/' + req.headers["accept-language"].substr(0, 2).toLowerCase());
} catch(err) {
    console.log("no language found - falling back to english");
    var words = require('../languages/en');
}

res.render('index', { language: words });
};

now, I am pretty sure there's something wrong there. as I think requiring should be done once only, and I am requiring it with each request. But, I can't think of any other way since I need to access the language in the request header.

Any ideas?

Thanks in advance.

For internationalization, I would highly recommend i18n.

i18n-node

You are requiring two different files. So am not sure why you think you a repeating yourself.

Eventually you should turn you language file into a actual module that's located in a local node_modules folder or in the same node_modules your app uses.

This way you can require you language module like this.

var language = require('language');

Inside you language module there should be a index file and lib directory.

index.js

exports.en= require('./lib/en'),
exports.fr= require('./lib/fr'),
exports.de= require('./lib/de'),

Then you will be able to use your module like this.

exports.index = function(req, res){

  language = require('language');

try {

    var words = language[req.headers["accept-language"].substr(0, 2).toLowerCase()]();
} catch(err) {
    console.log("no language found - falling back to english");
    var words = language.en();
}

res.render('index', { language: words });
};

REPLACE above with this.

exports.index = function(req, res){

    var language = require('language');
        supported_languages = ['en', 'fr' , 'de'],
        accept_language = req.headers["accept-language"].substr(0, 2).toLowerCase();

    if(supported_languages.indexOf(accept_language) !== -1){

        var words = language[accept_language]();

    }else {
        console.log("no language found - falling back to english");
        var words = language.en();
    }

    res.render('index', { language: words });    
};