Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 743
Nikola Avatar asked Jan 12 '15 20:01

Nikola


People also ask

Can you use import with module exports?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.

Can I export a variable in JavaScript?

Use named exports to export multiple variables in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported variables can be imported by using a named import as import {A, B} from './another-file.


Video Answer


1 Answers

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).

like image 134
Vsevolod Goloviznin Avatar answered Oct 14 '22 05:10

Vsevolod Goloviznin