The Real David Powell The Real David Powell - 4 months ago 6
Javascript Question

Why can't I set an exported variable in one file from another in Node.js?

Consider these two programs:

testing1.js:

'use strict';
var two=require('./testing2');

two.show();
two.animal='Dog';
two.show();


testing2.js:

'use strict';
var animal='Cat';

function show()
{
console.log(animal);
}

module.exports.animal=animal;
module.exports.show=show;


When I run this in Node.js, it prints "Cat Cat". I expected it to print "Cat Dog". Why did it print "Cat Cat", and how can I make it print "Cat Dog"?

Answer

I think the problem here is that two.animal and var animal are two different variables. The show function is always logging the var animal that was defined in testing2.js

For testing2.js I would do something like this:

'use strict';

module.exports = {
    animal: 'Cat',
    show: function () {
        console.log(this.animal); // note "this.animal"
    }
}

Then in testing1.js:

'use strict';

var two = require('./testing2.js');

two.show(); // => Cat
two.animal = 'Dog'; // now replaces 'Cat'
two.show(); // => Dog
Comments