0

firstly, my English skill is poor i`m sorry about that

i made this code for hide private functions & vars from other

DB_OBJ.js

module.exports = (function() {
var _mysql = require('mysql');
var _self = null;
var _connFlag = false;

var _mysqlConfig = {
    host: "127.0.0.1",
    port: 3306,
    user: "tester",
    password: "*****",
    database: "*****"
};

var _conn = null;

var _init = function(){
    _conn = _mysql.createConnection(_mysqlConfig);

    _conn.connect(function(err) {              
        if (err) {    
            console.log(err);
        }
        _connFlag = true;
    });

};



var db_obj = function (args) {
    _self = this;

    if (args) {
        _mysqlConfig.host = (args["host"]) ? args["host"] : "127.0.0.1";
        _mysqlConfig.port = (args["port"]) ? args["port"] : "3306";
        _mysqlConfig.user = (args["user"]) ? args["user"] : "*****";
        _mysqlConfig.password = (args["password"]) ? args["password"] : "*****";
        _mysqlConfig.database = (args["database"]) ? args["database"] : "*****";
    }

    this.init = function () {
        _init();
    };

};

return db_obj;

})();

main.js

var db_obj = new require('./DB_OBJ');
db_obj.init();

but this code error occur it:

TypeError: db_obj.init is not a function

please. let me know how can i fix it?

Thanks.

  • There's quite a bit of weirdness in this code (vars that don't get used, functions empty function wrapping, an init function that completely ignores the args you're passing in, etc). What is this module supposed to do? Instead of doing this weird thing, just create an object for setting up a connection, and have your module return that. Start with something like this? http://jsbin.com/hepuwoxeke/edit?js,output – Mike 'Pomax' Kamermans Jan 21 '16 at 05:11
  • it is just some of all, full code is too much lines. i added some more codes 'used args var' to more clear it – Albert Yun Jan 21 '16 at 05:25
  • @AlbertYun, nothing returns in `db_obj`... I have updated my answer... – zangw Jan 21 '16 at 05:36

2 Answers2

0

I would refactor it to look like this example. I dont you think you want to wrap the exports function in an anonymous function. Remove the ()();

What is the purpose of Node.js module.exports and how do you use it?

Community
  • 1
  • 1
Bob
  • 780
  • 9
  • 10
0

Change your db_obj as below

var db_obj = function (args) {
    _self = this;

    if (args) {
        _mysqlConfig.host = (args["host"]) ? args["host"] : "127.0.0.1";
        _mysqlConfig.port = (args["port"]) ? args["port"] : "3306";
        _mysqlConfig.user = (args["user"]) ? args["user"] : "*****";
        _mysqlConfig.password = (args["password"]) ? args["password"] : "*****";
        _mysqlConfig.database = (args["database"]) ? args["database"] : "E3MultiCore_v1";
    }

    _self.init = function () {
        _init();
    };

    return  _self;
};

In main.js

var db_obj = new require('./DB_OBJ');

db_obj().init();
zangw
  • 43,869
  • 19
  • 177
  • 214