简体   繁体   English

在 Node.Js / Express 应用程序中存储数据库配置的最佳方式

[英]Best way to store DB config in Node.Js / Express app

What would be the best way to store DB config (username, password) in an open source app that runs on node.js / Express?在 node.js / Express 上运行的开源应用程序中存储数据库配置(用户名、密码)的最佳方式是什么? Two specific questions:两个具体问题:

  1. Shall I put it into a separate config.js file in /lib folder, for example, and never include it into the master repository that is publicly available on GitHub?例如,我是否应该将它放入/lib文件夹中的单独 config.js 文件中,并且永远不要将其包含在 GitHub 上公开可用的主存储库中?

  2. To inlcude the config, is it as simple as require('./config.js') from the file that needs it or is there a better way of doing it?要包含配置,它是否像需要它的文件中require('./config.js')一样简单,还是有更好的方法?

PS sorry if the questions seem a bit simple or not so well formulated, but I'm just starting:) PS 抱歉,如果问题看起来有点简单或表述不太好,但我才刚刚开始:)

Here's how I do it: 我是这样做的:

Create a config.js which contains objects representing your configs: 创建一个config.js,其中包含代表您的配置的对象:

var config = {
development: {
    //url to be used in link generation
    url: 'http://my.site.com',
    //mongodb connection settings
    database: {
        host:   '127.0.0.1',
        port:   '27017',
        db:     'site_dev'
    },
    //server details
    server: {
        host: '127.0.0.1',
        port: '3422'
    }
},
production: {
    //url to be used in link generation
    url: 'http://my.site.com',
    //mongodb connection settings
    database: {
        host: '127.0.0.1',
        port: '27017',
        db:     'site'
    },
    //server details
    server: {
        host:   '127.0.0.1',
        port:   '3421'
    }
}
};
module.exports = config;

Then in my index.js (or wherever really), 然后在我的index.js(或任何地方),

var env = process.env.NODE_ENV || 'development';
var config = require('./config')[env];

Then process with that object, eg 然后用该对象处理,例如

var server = express();
server.listen(config.server.port);
...

Not sure whether this is the best practice, but personally I have a config.json file where I store my db connection information. 不确定这是否是最佳做法,但我个人有一个config.json文件,我存储我的数据库连接信息。 Then I do the following: 然后我做以下事情:

// options.js
var fs = require('fs'),
configPath = './config.json';
var parsed = JSON.parse(fs.readFileSync(configPath, 'UTF-8'));
exports.storageConfig=  parsed;

Then from a different file I do the following: 然后从另一个文件中执行以下操作:

var options = require('./options');

var loginData = {
        host: options.storageConfig.HOST,
        user: options.storageConfig.user,
        password: options.storageConfig.password
};

For running toy apps where I need to hide db credentials, I use the dotenv module . 对于运行我需要隐藏数据库凭据的玩具应用程序,我使用dotenv模块

Place your sensitive info in a .env file (which is .gitignored), place require('dotenv').config(); 将敏感信息放在.env文件(.gitignored)中,放置require('dotenv').config(); in your app; 在你的应用程序; dotenv creates entries in process.env that you can refer to. dotenv在process.env中创建您可以参考的条目。

.env file: .env文件:

DATABASE_PASSWORD=mypw
DATABASE_NAME=some_db

To refer to the values: 要引用这些值:

process.env.DATABASE_PASSWORD

I do put in args. 我确实放了args。 just like the port of so many node.js example. 就像这么多node.js例子的端口一样。 you most likely forever, pm2, nodemon to run your app. 你最有可能永远,pm2,nodemon来运行你的应用程序。 so this variable is not check in as part of your source code. 因此,此变量不会作为源代码的一部分签入。 and they are globally available too. 它们也是全球可用的。

process.env.PORT
process.env.DATABASE_USER
process.env.DATABASE_PASSWORD


PORT=3000 DATABASE_HOST=localhost DATABASE_USER=admin DATABASE_PASSWORD=mypassword node app.js

export PORT=3000
export DATABASE_HOST=localhost
export DATABASE_PORT=27017
export DATABASE_USER=admin
export DATABASE_PASSWORD=mypassword
node app.js

var server = app.listen(process.env.PORT, function() {
});

var mongoClient = new MongoClient(new Server(process.env.DATABASE_HOST, process.env.DATABASE_PORT));

To inlcude the config, is it as simple as require('./config.js') from the file that needs it or is there a better way of doing it? 要包含配置,它是否需要来自需要它的文件中的require('./ config.js'),或者有更好的方法吗?

This is the right way to store config files. 这是存储配置文件的正确方法。

The best approach would be to write your entire application like an ordinary node.js module, and write a small start-up file that calls it. 最好的方法是将整个应用程序编写为普通的node.js模块,并编写一个调用它的小型启动文件。 This idea also allow you to use different database drivers using dependency injection. 这个想法还允许您使用依赖注入使用不同的数据库驱动程序。

Good, but not perfect solution is the environment. 良好但不完美的解决方案是环境。 It is shared among all application, so if you have certain data you want to be available to all of them, this is the best bet. 它在所有应用程序之间共享,因此如果您希望所有数据都可以使用某些数据,那么这是最好的选择。 But if you have a config for one particular app, not much so. 但是,如果你有一个特定应用程序的配置,不是那么多。

PS: And please, don't use JSON for this. PS:请不要使用JSON。 It's the worst idea possible. 这是最糟糕的想法。 :) :)

I found this a nice way to handle my config, considering different environments: 考虑到不同的环境,我发现这是处理配置的好方法:

config.coffee config.coffee

exports.setEnvironment = (env) ->
    switch env
        when "development"
            exports.DEBUG_LOG = true
            exports.DB_PORT = '27017'
            # ...
        when "testing"
            exports.DEBUG_ERROR = true
            exports.DEBUG_CLIENT = true
            # ...
        when "production"
            exports.DEBUG_LOG = false
            # ...
        else console.log "environment #{env} not found"

server.coffee: server.coffee:

config = require('./config')
config.setEnvironment env
  1. Using environment variables使用环境变量

You can use export to set environment variables in OSX and Linux. The following is an example of setting a value in the SESSION_SECRET key.在OSX和Linux中可以使用export设置环境变量,下面是在SESSION_SECRET键中设置值的例子。

export SESSION_SECRET="keyboard cat"

In Windows, you can use set.在Windows,可以用set。

set SESSION_SECRET="keyboard cat"

You can also set environment variables each time you run them.您还可以在每次运行它们时设置环境变量。

SESSION_SECRET="keyboard cat" node secret-env.js

Use process.env of node.js to access environmental variables within code.使用 node.js 的 process.env 访问代码内的环境变量。

var express = require('express')
var session = require('express-session')
var app = express()
app.use(session({secret: process.env.SESSION_SECRET}))
  1. Request a argument from the command-line从命令行请求参数

The best way to protect confidential information is not to store it in a setup file.保护机密信息的最佳方法是不要将其存储在安装文件中。 If the command-line requests configuration information as an argument using the noopt package, the secret information does not need to exist as a file.如果命令行使用 noopt package 请求配置信息作为参数,则机密信息不需要作为文件存在。 The following is an example of requesting a session key as an argument using the noopt package.以下是使用 noopt package 请求 session 密钥作为参数的示例。

var nopt = require("nopt")

var longOpts = {
  "sessionSecret": String,
}

var shortOpts = {
  "s": ["--sessionSecret"],
}

var parsed = nopt(longOpts, shortOpts, process.argv, 2)

console.log("session secret is:", parsed.sessionSecret)
node secret-arg.js --sessionSecret "keyboard cat"
node secret-arg.js -s "keyboard cat"

Advantages: It is safer to expose confidential information than to hardcoding or having it as a configuration file.优点:公开机密信息比硬编码或将其作为配置文件更安全。

Disadvantages: There is a hassle of increasing the amount of information to be entered each time the app is launched.缺点:增加了每次启动应用时需要输入的信息量,带来麻烦。 If you try to create and solve a script, the problem that the password still exists in the script remains.如果您尝试创建和解决脚本,密码仍然存在于脚本中的问题仍然存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM