Answer the question
In order to leave comments, you need to log in
How to put the nodejs server settings into a separate file?
Hello.
Sorry for a possibly stupid question, but still tell a beginner how to do it right.
I have a nodejs express project, I plan to deploy it on several machines, and in order not to climb into the server code every time, I want to create a settings file (server ip, port ....,) how can I do it right?
P.S. : And how can you transfer data from this config to client-side JavaScript, from the public folder, connected to index.ejs ?
Answer the question
In order to leave comments, you need to log in
There is no right way, there are many different ones, all of them are wrong. I offer two of the wrong ways to choose from:
config.js file:
module.exports = {
host: 'hostname',
port: 80
};
// Подключение конфига
var config = require('./config.js');
// Использование конфига
console.dir(config);
{
"host": "hostname",
"port": 80
}
// Подключение конфига
var config = require('./config.json');
// Использование конфига
console.dir(config);
config.js
var config = {}
config.database = {};
config.server= {};
config.database.user = '';
config.database.password = '';
config.database.server = '';
config.database.database =
config.database.options = {
};
config.server.port = ;
module.exports = config;
var appConfig = require('./server/config/config');
...
app.set('port', appConfig.server.port || 8080);
...
In addition to the above, I suggest using ENV variables to store that part of the configs that depends on the environment (hosts, ports, passwords).
And how can you transfer data from this config to client-side JavaScript, from the public folder, connected to index.ejs ?
I do like this: example and description . The meaning is about the same as in Django applications: config is code, import the module depending on some environment variable, ./local.js takes precedence over everything else.
Advantages: very flexible; you can "inherit" from each other and redefine configs in any combination; no need to learn another config language (preved yaml) and no need to put up with its shortcomings (preved jason).
Disadvantages: not declarative; there is no npm module, so out of the box; require caches connected modules, so you have to dance with a tambourine to update the config on the fly.
Is the given syntax valid for the new fifth node? otherwise I’ll see everything becomes obsolete faster than shit coded by developers
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question