Search code examples
javascriptnode.jsdefineproperty

Update JS define property from outside


I use the following code and I want from other module to update some property,how should I do that?

This is the module code(In real there is more properties...)

"use strict"
function define(name, value) {
    Object.defineProperty(exports, name, {
        value:      value,
        enumerable: true
    });
}

define("USER_PATH","oldValue");

Now I require it from other module and I want to update the key USER_PATH to be with "newValue".

I try to require this module and do like following which doesnt change the value in the USER_PATH,in the debugger I see the "oldValue"

var foo = require("theAboveModule")
foo.USER_PATH = "test";

Solution

  • Throw a writable: true in there:

    function define(name, value) {
        Object.defineProperty(exports, name, {
            value:      value,
            enumerable: true,
            writable: true
        });
    }
    

    Here's a jsbin where you can see it working: http://jsbin.com/burifi/edit?js,console