Nikola
Nikola

Reputation: 15048

How to reference a variable inside a module.exports in Node.js

I have a module written like below:

module.exports = {
    port: '1337',
    facebook: {
        clientID: '123456789',
        clientSecret: 'a1b2c3d4e5f6g7h8i9j0k',
        callbackURL: 'http://localhost:1337/oauth/facebook/callback'
    }
};

What I would like to do is use the port variable in the callbackURL:

callbackURL: 'http://localhost:1337/oauth/facebook/callback'

I tried:

callbackURL: 'http://localhost:'+ this.port +'/oauth/facebook/callback'

but obviously that's not correct since the facebook is another object. So, can someone solve this one, and please any additional reading that you have (in terms of deeper understanding) is welcome.

Upvotes: 8

Views: 6235

Answers (2)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12334

Just declare it above the module.exports as an ordinary variable:

var port = '1337';
module.exports = {
    port,
    facebook: {
        clientID: '123456789',
        clientSecret: 'a1b2c3d4e5f6g7h8i9j0k',
        callbackURL: 'http://localhost:'+ port + '/oauth/facebook/callback'
    }
};

You can put module.exports wherever you want in your file, you can even perform some logic (like retrieving settings from a file or another resource).

Upvotes: 15

Jose Quijada
Jose Quijada

Reputation: 690

I use the below construct all the time,

const that = module.exports = {
    port: '1337',
    facebook: {
        clientID: '123456789',
        clientSecret: 'a1b2c3d4e5f6g7h8i9j0k',
        callbackURL: `http://localhost:${that.port}/oauth/facebook/callback`
    }
};

Even if you were trying to use this.port in the outermost object, it still will not give the desired results, because the this will not point to the object you're exporting in the module.exports. I'm not sure of the answer to this - no pun intended. I'm still researching and experimenting to find out more, can report back once I know more.

Upvotes: 2

Related Questions