0

How can I pass the variables port,host,database into this function?

//myjs.js

var redisCaller = function(port,host,database){

};

module.exports = new redisCaller();

if I do:

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

how do I pass those variables?

seems like the only way to do it is like this:

module.exports = function(port,host,database){

    return new redisCaller(port,host,database);
}

2 Answers 2

3

Change myjs.js to:

module.exports = redisCaller;

Then you can do:

var myjs = require('./myjs')(port,host,database);

Sign up to request clarification or add additional context in comments.

3 Comments

@AlexMills You probably don't want to be returning a new call every time you require your module though. Or maybe you do?
yes, you're right, for a singleton, you'd want to always return the same object, I will change the title
this doesn't appear correct when I try it, the edit I made in the OP does work though
1

You don't.

The way you've set up that code makes it impossible to pass variables in, unless you tweak the require. Which then makes you potentially have to know about the port/host/database in any file you use it in.

Instead, maybe just use an 'init'.

For example, app.js -

var redisCaller = require('./myjs');
redisCaller.init(port, host, database);

And the myjs..

var redisCaller = function(){
    this.init = function (port,host,database) {
        this.connection = ...
    }
    this.getConnection = function () {
        if(!this.connection) { throw "Need to run init first"; }
        return this.connection;
    }
};

module.exports = new redisCaller();

Anywhere you need the connection...

var redisCaller = require('./myjs');
var conn = redisCaller.getConnection();

//or 

var redisCaller = require('./myjs').getConnection();

It's a bit more code, but at least it's easy to reuse across files.. assuming that was your intention.

1 Comment

see my edit and Tony's answer, I think you can tweak it to make it work easily. But your answer will also work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.