Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 447 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Where do I put database connection information in a Node.js app?

#1
Node.js is my first backend language and I am at the point where I am asking myself "where do I put the database connection information?".

There is a lot of good information regarding this issue. Unfortunately for me all the examples are in PHP. I get the ideas but I am not confident enough to replicate it in Node.js.

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

How would 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 = "[email protected]"');

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 basic express application with 1 GET route. This route sets off the function to go to the database and pull out information based on an email address.

At the top of the GET route is the database connection information. Where do I put that? How do I call it? How do I keep it out of web root, and include it like PHP ? Can you please show me in a working example. Thanks!
Reply

#2
I agree with the commenter, put it in a config file. There is no ultimate way, but [nconf](

[To see links please register here]

) is also one of my favourites.

The important best practise is that you keep the config separate if you have a semi-public project, so your config file will not overwrite other developers.

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

#3
I use the Express Middleware concept for same and that gives me nice flexibility to manage files.

I am writing a detailed answer, which includes how i am use the config params in app.js to connect to DB.

So my app structure looks something this: ![enter image description here][1]



How i connect to DB? (I am using MongoDB, mongoose is 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();


under the config folder i also have 'env' folder, which stores the environment related configurations in separate files such as development.js, test.js, production.js

Now as the name suggests, development.js stores the configuration params related to my development environment and same applies to the case of test and production. Now if you wish you can have some more configuration setting 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's into, username, password, port, database, hostname.

For For more details have a look at [my repo][2], where you can find this implementation, in fact now in all of my projects i use the same configuration.

If you are more interested then have a look at [Mean.js][3] and [Mean.io][4], they have some better ways to manage all such things. If you are beginner i would recommend to keep it simple and get things going, once you are comfortable, you can perform magic on your own. Cheers


[1]:

[2]:

[To see links please register here]

[3]:

[To see links please register here]

[4]:

[To see links please register here]

Reply

#4
I recommend the 12-factor app style

[To see links please register here]

which keeps all of this in env vars. You never should have this kind of information hard-coded or in the app source-code / repo, so you can reuse it in different environments or even share it publicly without breaking security.

However, since there are lots of environment vars, I tend to keep them together in a single `env.js` like the previous responder wrote - although it is not in the source code repo - and then source it with

[To see links please register here]


An alternative is to do it manually and keep it in, e.g. `./env/dev.json` and just `require()` the file.

Any of these works, the important point is to keep all **configuration** information separate from **code**.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through