Where should the database configuration file be located in Node.js and Express?

Now I'm learning Node.js and Express and want to use the mysql module to render several unique pages, so instead of writing the line var connection=mysql.createConnection({user:'root', password: 'root'...etc}) for each file located in the routes directory, I am sure that it is best to just call my own mysql configuration file in each routing file.

However, where should I put the configuration file in the Express hierarchy and how can I call the file from each routing file? I know that all images, stylesheets and javascript files should be located in each specific directory in the public directory, but I do not know where to put all the other files that need to be accessed from the routing files.

I also want to know if all my files, from the main app.js to the files in the routes directory to the files in the public directory, etc ..., will be after I publish this web application on the Internet. If so, then I think I should not put the database configuration file in directories that clients can access ... right? In other words, I want to make sure which files clients can access and which not to avoid security attacks.

+4
source share
2 answers

To answer your first question, “Where to put the configuration file?”: This is a bit individual. Put it at the root of your application.

config.js:

 module.exports = { database:{ host: "" user: "..." } } 

then you include it in the app.js application:

app.js:

 ... config = require("./config"); db = config.database; var connection=mysql.createConnection({user:db.user, ...}) 

Note that you may need two configuration files: one in your version control and one private for the machine. For example, different developers may have different access to the database. But I don’t think you should worry about it now.

For your second question, “Are all my files publicly available?”: No, only the file that you specify as static will be provided (using middleware).

app.js:

 ... // Exposes the public folder app.use(express.static(__dirname + '/public')); 
+10
source

You can place them wherever you want. Usually I create the /conf directory directly from the project root and put the configuration files in JSON format there.

0
source

Source: https://habr.com/ru/post/1485691/


All Articles