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.
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);
});
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With