I'm now learning Node.js and Express, and want to call mysql module to render multiple unique pages, so instead of writing out var connection=mysql.createConnection({user:'root', password: 'root'...etc}) line on all files located under routes directory, I think I should call my own mysql config file on the first or second (after the line of requiring mysql module) line on each routing file. However, where should I put the config file on Express hierarchy and how can I call the file from within each routing file? I know all images, style sheets, and javascript files should be located within each specific directory under public directory, but don't know where to put all the other files that should be intended to be accessed from routing files.
I also want to know whether all of my files, ranging from main app.js to files under routes directory to files under public directory, etc... can be found by users once I publicize this web application on the Web. If it's the case, then I think I should not put database config file on directories that clients can access to...right? In other words, I want to make sure which files can be accessed to by clients and which cannot in order to avoid security attacks.
Thanks.
To answer your first question "Where to put the config file?": This is a little bit personnal. Put it to the root of your application.
config.js:
module.exports = {
database:{
host: ""
user: "..."
}
}
then you include it in you app.js:
app.js:
...
config = require("./config");
db = config.database;
var connection=mysql.createConnection({user:db.user, ...})
Note that you might want two config file, one in you version control and one private to the machine. Different developers might have different database access for example. But I don't think you have to worry about that for now.
For your second question "Are all my files public?": No, only the file you specify as static (with the express middleware) will be served.
app.js:
...
// Exposes the public folder
app.use(express.static(__dirname + '/public'));
You can put them wherever you want. I usually create a /conf directory right off the project root and put config files in there, in JSON format.