1

I have a config file for my Node.js application which looks like this:

// Development specific configuration
// ==================================
module.exports = {

....

  ip: "localhost",
  //Rabbit MQ
  rabbitmq: {
    username: 'foo',
    password: 'bar',
    ip: 'amqp://'+this.username+':'+this.password+'@rabbitmq',
    queues: {
      name: 'foo'
    }
  }, 
....

};

Here is what the module looks like where I use this config file:

var config = require ('../../config/environment');
this.con = amqp.connect (config.rabbitmq.ip);

I am getting undefined for the username and password:

amqp://undefined:undefined@rabbitmq

I have tried multiple ways such as:

  1. Creating getter functions inside the object like this:

    rabbitmq: {
    username: 'foo',
    password: 'bar',
    getUsername: function (){
       return this.username;
    },
    getpassword: function (){
       return this.password;
    },
    ip: 'amqp://'+this.getUsername()+':'+this.getpassword()+'@rabbitmq',
    
  2. Created a self value and assign 'this' and reference it:

    self: this,
    ...
    ip: 'amqp://'+self.rabbitmq.username+':'+self.rabbitmq.password+'@rabbitmq',
    

    ..

I cannot get the scope to properly work. Am I missing something basic? How can I make this happen? Please help.

TitaniuM
  • 321
  • 1
  • 10
  • 19
  • Can you try this ip: 'amqp://'+username+':'+password+'@rabbitmq', – Sailesh Babu Doppalapudi Apr 19 '17 at 02:36
  • ip: 'amqp://'+username+':'+password+'@rabbitmq', ^ ReferenceError: username is not defined – TitaniuM Apr 19 '17 at 03:06
  • Being a part of an expression - `this` holds the value of the current scope you're running at. So what you want to do is not possible (and is not necessary to be honest). – zerkms Apr 19 '17 at 03:15
  • Possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – t.niese Apr 19 '17 at 06:25

2 Answers2

0

This will work:

var username = 'foo';
var password = 'bar';

module.exports = {
  ip: "localhost",
  //Rabbit MQ
  rabbitmq: {
    username: username,
    password: password,
    ip: 'amqp://'+username+':'+password+'@rabbitmq',
    queues: {
      name: 'foo'
    }
  }
};
zerkms
  • 249,484
  • 69
  • 436
  • 539
Jake Lampack
  • 141
  • 1
  • 6
0

You can do something like this:

var config = {
    ip : "localhost", //Rabbit MQ
    rabbitmq : {
        username : 'foo',
        password : 'bar',
        queues : {
            name : 'foo'
        }
    }
};

config is now declared in module scope so you can reuse its values

config.rabbitmq.ip = 'amqp://' + config.rabbitmq.username + ':' + config.rabbitmq.password + '@rabbitmq';
module.exports = config;
ponury-kostek
  • 7,824
  • 4
  • 23
  • 31