The Real David Powell The Real David Powell - 9 months ago 30
Javascript Question

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

Consider these two programs:


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


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

function 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"?


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');; // => Cat
two.animal = 'Dog'; // now replaces 'Cat'; // => Dog