最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trouble with Node.js constants - Stack Overflow

programmeradmin2浏览0评论

I'm currently learning Node.js and I'm having trouble integrating constants into my service. I have created a constants file and am referencing those values from other files. Unfortunately, I don't seem to be doing it correctly as things start to fail when I reference constants rather than just place literals into all of my function calls.

constants.js

exports.DB_HOST = 'localhost';
exports.DB_PORT = 3306;
exports.DB_USER = 'user';
exports.DB_PASSWORD = 'password';
exports.DB_DATABASE = 'database';

When trying to connect to a MySQL database, the connection fails as the server claims that the credentials are incorrect. However, when I replace all of the constants below with literals, everything works correctly (so I'm not using incorrect authentication information).

var constants = require('constants');

...

var connection = mysql.createConnection({
    host: constants.DB_HOST,
    port: constants.DB_PORT,
    user: constants.DB_USER,
    password: constants.DB_PASSWORD,
    database: constants.DB_DATABASE
});

...

connection.query('SELECT * FROM table',
    function(err, rows, fields) {
        res.send(err);
});

I'm currently learning Node.js and I'm having trouble integrating constants into my service. I have created a constants file and am referencing those values from other files. Unfortunately, I don't seem to be doing it correctly as things start to fail when I reference constants rather than just place literals into all of my function calls.

constants.js

exports.DB_HOST = 'localhost';
exports.DB_PORT = 3306;
exports.DB_USER = 'user';
exports.DB_PASSWORD = 'password';
exports.DB_DATABASE = 'database';

When trying to connect to a MySQL database, the connection fails as the server claims that the credentials are incorrect. However, when I replace all of the constants below with literals, everything works correctly (so I'm not using incorrect authentication information).

var constants = require('constants');

...

var connection = mysql.createConnection({
    host: constants.DB_HOST,
    port: constants.DB_PORT,
    user: constants.DB_USER,
    password: constants.DB_PASSWORD,
    database: constants.DB_DATABASE
});

...

connection.query('SELECT * FROM table',
    function(err, rows, fields) {
        res.send(err);
});
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jan 9, 2016 at 23:08 Jack HumphriesJack Humphries 13.3k14 gold badges85 silver badges132 bronze badges 3
  • is your mysql running ? – Phoenix Commented Jan 9, 2016 at 23:11
  • @Phoenix Yes - as I said, everything works correctly when I replace the constant names with literals. – Jack Humphries Commented Jan 9, 2016 at 23:13
  • Unrelated to the answers below, I would advise against requiring a file called constants. Consider naming it DatabaseConstants or DBConstants – Stephan Bijzitter Commented Jan 9, 2016 at 23:59
Add a ment  | 

3 Answers 3

Reset to default 5

constants is a built-in node module that provides system-level constants for use with other built-in modules, like fs, crypto, etc. If you want your constants.js, you will need to include the (absolute or relative) path to it. For example:

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

In addition to changing your require() to use your local module rather than a built-in module:

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

There is a misspelling here in your code:

port: constants.DB_POST,
//  wrong character  ^ 

should be:

port: constants.DB_PORT,

So, a couple things:

  • It looks like you're trying to require either an installed node module called constants or a built-in module (which is pretty much a set of constants for us in built-in node modules like fs, http, crypto, etc.). That would be the main reason you can't access it. Node doesn't know to look for your local module b/c no path string has been supplied.

  • you might be able to clean up your module a bit w/ some optional but (sometimes) helpful refactoring.

I would remend the following change to how you require your module:

// Bc it's a set of constants, use the es6/2015 `const` if available when requiring your module
const constants = require('./constants');

You could clean up your module a little bit w/ module.exports; makes it really clear what the object you're exposing is:

module.exports = {
  DB_HOST : 'localhost',
  DB_PORT : 3306,
  DB_USER : 'user',
  DB_PASSWORD : 'password',
  DB_DATABASE : 'database',
}

Another consideration: in most apps, you really want to keep configuration as internally-stateless as possible. That means your app shouldn't really have any configurational values hard-coded into it. Generally, if you avoid doing so you will have a much more flexible setup externally. In other words, you'd be able to spin up as many different instances as you want with as many different databases to connect to. When you change databases, you'd only have to change the environment, not the app itself. And, if you get into the semantics of it all, your app's job is to connect, not to really decide where to connect — the environment should provide that. So, these could be made available from your module as:

const config = {
  DB_HOST : process.env.DB_HOST,
  DB_PORT : process.env.DB_PORT,
  DB_USER : process.env.DB_USER,
  DB_PASSWORD : process.env.DB_PASSWORD,
  DB_DATABASE : process.env.DB_DATABASE,
};
module.exports = config;

You could just access them from anywhere with process.env.YOUR_VAR, but if you want to consolidate them all in a module that is just as good in many ways and would let you change external config value variable names (i.e. process.env.DB_USERNAME instead of DB_USER) and not have to change it everywhere else (if you don't need the names to be kept in sync).

Hope that helps! :)

发布评论

评论列表(0)

  1. 暂无评论