whitfin
whitfin

Reputation: 4629

Overwriting value of a key in module.exports

I'm trying to store a value in a Helper file, which is calculated after the initial require of the Helper, and the value doesn't change from undefined (because it was unknown to start with).

Is there any way I can overwrite this value to use elsewhere?

helper.js:

module.exports = {
    key:value
}

setup.js:

var helper = require("./helper.js");

... // hit a url and get a value
helper.key = newValue;

usage.js:

var helper = require("./helper.js");

console.log(helper.value) // prints the original value

Flow

setup.js -requires-> helper.js
usage.js -requires-> helper.js

I've read that module.exports is seemingly read-only, but surely there must be a way to do this.

Also, is it possible to add to module.exports after the initial creation?

module.exports["key"] = value;

Thanks in advance, seems like it should be simple but it's a roadblock for me.

EDIT: Ignore the second question, I have gotten this work (about the module.exports["key"]).

Upvotes: 1

Views: 868

Answers (1)

ZenMaster
ZenMaster

Reputation: 12742

I am not sure there is an issue here. May be I don't understand the loading flow and there is some crazy scope configuration...

You can do it like this and you can alter the exports (whether this is a feature, is a different matter).

Imagine these modules:

test1.js

module.exports = {
    a: '1'
}

test2.js

var test1 = require('./test1');

module.exports = function() {
    test1.a = test1.a + '2';
    test1.b = 100;
};

test3.js

var test1 = require('./test1');

module.exports = function() {
    test1.a = test1.a + '3';
    test1.b = 200;
};

test4.js

var test2 = require('./test2')();
var test3 = require('./test3')();
var test1 = require('./test1');

console.log(test1);

The output, when running node test4 is:

{ a: '123', b: 200 }

or, if you switched the order of loading of modules 2 and 3 in module 4:

var test2 = require('./test3')();
var test3 = require('./test2')();
var test1 = require('./test1');

console.log(test1);

it would become:

{ a: '132', b: 100 }

Upvotes: 1

Related Questions