Search code examples
javascriptnode.jsmiddleware

Import dynamic folder depending on req.headers['accept-language']


I'm trying to implement a new feature - sending multi-language mail with Nodejs.

I have directory structure like this:

mail-templates
__index.js
__jp
____index.js
____mail1.js
____mail2.js
__en
____index.js
____mail1.js
____mail2.js

In index of en and jp, I will import and export all files in current folder

In index of mail-teamplates, I want to dynamically import folder depending on req.headers['accept-language'] like this:

import * as Mail from `./${variable}` // variable are en or jp depending on accept-language

My question: How I can do that? How I can get accept-language at here to dynamically import folder ?


Solution

  • Is not recommended to do that inside a http callback. The best solution for your problem is to import all of the available languages and just use the preferred language for each request.

    Example:

    In your mail-templates/index.js:

    import * as en from './en';
    import * as es from './es';
    
    const defaultLanguage = 'en';
    const availableLanguages = { en, es }; 
    
    function getMailByLanguage(language) {
        return availableLanguages[language] || availableLanguages[defaultLanguage];
    }
    
    module.exports = getMailByLanguage;
    

    And when you want to use it, just do this:

    import * as MailTemplates from './mail-templates';
    
    app.get("/", (req, res) => {
        const language = req.headers["language"];
        const Mail  = MailTemplates.getMailByLanguage(language);
    
        // Do your stuff's here
        ...
    });