How to use helpers in Node.js to load settings?

Asked

Viewed 349 times

1

In the Laravel Framework we have the configuration files centralized in the directory /config, these are simple files php returning a array key and value.

To access these settings anywhere in the application we can use the Helper config, therefore, when using config('app.timezone'); we can access the contents of /config/app.php, key timezone and return the value of this.

How could it have a similar behavior in nodejs, preferably using a Helper as simple as the one mentioned above?

Note: if relevant, I am using Express.js in the project.

1 answer

0

You create a configuration file .js, this file containing module.exports of the data you intend to use. As an example:

app.config.js

module.exports = 
{
    webPort: 80,
    database:
    {
         url : "mongodb://localhost/app",
         user : "admin",
         password : "1234"
    }
}

Preferably this file will be in the root of the project. To access it, just give a require:

const config = require("./app.config.js") //Considerando esteja no mesmo diretório.
  • Could you point me to an autoloader that allows me to dynamically "require"? I would like to import into root something that when called invokes the corresponding file, example: config(‘app.port'). In short, the function would consider app as archive and port as key, for the previous example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.