Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with Node.js constants

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);
});
like image 893
Jack Humphries Avatar asked Apr 26 '26 18:04

Jack Humphries


2 Answers

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');
like image 190
mscdex Avatar answered Apr 29 '26 09:04

mscdex


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,
like image 30
jfriend00 Avatar answered Apr 29 '26 11:04

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!