Where can I put database connection information in a Node.js application?

Node.js is my first backend language, and I am at the point where I ask myself: "Where can I put database connection information?".

There is a lot of good information on this issue. Unfortunately, for me all the examples are in PHP. I get ideas, but I'm not sure enough to reproduce it in Node.js.

In PHP, you put information in a configuration file outside the root website and include it when you need database data.

How do you do this in Node.js? using the Express.js framework.

So far I have this:

var express = require('express'), app = express(); var mysql = require('mysql'); app.get('/', function(req,res) { var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'store' }); var query = connection.query('SELECT * from customers where email = " deelo42@gmail.com "'); query.on('error', function(err) { throw err; }); query.on('fields', function(fields) { console.log('this is fields'); }); query.on('result', function(row) { var first = row.first_name; var last = row.last_name; res.render('index.jade', { title: "My first name is " + first, category: "My last name is " + last }); }); }); app.listen(80, function() { console.log('we are logged in'); }); 

As you can see, I have a main express application with 1 GET route. This route sets up a function to go to the database and display information based on the email address.

At the top of the GET route, database connection information is used. Where can I put this? What should I call it? How can I save it from the web root and enable it like PHP? Could you show me in a working example. Thanks!

+5
source share
3 answers

I use the Express Middleware concept for this, and it gives me good flexibility to manage files.

I am writing a detailed answer that includes how I use the configuration options in app.js to connect to the database.

So, my application structure looks something like this: enter image description here

How do I connect to the database? (I am using MongoDB, mongoose - ORM, npm install mongoose)

 var config = require('./config/config'); var mongoose = require("mongoose"); var connect = function(){ var options = { server: { socketOptions:{ keepAlive : 1 } } }; mongoose.connect(config.db,options); }; connect(); 

in the config folder, I also have the "env" folder, which stores environment-related configurations in separate files, such as development.js, test.js, production.js

Now, as the name suggests, development.js stores configuration parameters related to my development environment, and the same applies to the testing and production cases. Now, if you want, you can have more configuration settings, such as staging, etc.

project-name / config / config.js

 var path = require("path"); var extend = require("util")._extend; var development = require("./env/development"); var test = require("./env/test"); var production = require("./env/production"); var defaults = { root: path.normalize(__dirname + '/..') }; module.exports = { development: extend(development,defaults), test: extend(test,defaults), production: extend(production,defaults) }[process.env.NODE_ENV || "development"] 

project-name / config / env / test.js

 module.exports = { db: 'mongodb://localhost/mongoExpress_test' }; 

Now you can make it even more descriptive by breaking the URL, username, password, port, database, host name.

For more information, see my repo , where you can find this implementation, because now in all my projects I use the same configuration.

If you're more interested, check out Mean.js and Mean.io , they have some better ways to manage all of these things. If you are a beginner, I would recommend to keep it simple and achieve success, as soon as you feel comfortable, you can do the magic yourself. Greetings

+7
source

I recommend a 12-factor application style http://12factor.net that stores all this in env vars. You should never have such information hard-coded either in the source code / repository of the application so that you can reuse it in different environments or publicly publish it without compromising security.

However, since there are many environmental environments, I try to keep them together in a single env.js , as the previous responder wrote, although it is not in the source code repo repository and then sends it using https: //www.npmjs. org / package / dotenv

An alternative is to do it manually and save it, for example. ./env/dev.json and just require() file.

Any of these works is important to keep configuration information separate from the code .

+2
source

I agree with the commentator, put it in the configuration file. There is no way, but nconf is also one of my favorites.

An important good practice is that you save the configuration separately if you have a semi-public project, so your configuration file will not be overwritten by other developers.

 config-sample.json (has to be renamed and is tracked with for example git) config.json (not tracked / ignored by git) 
0
source

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


All Articles