2

How can I overwrite a module export value? Currently I have this:

temp.js

let lastrsss = '';


module.exports = {

    lastrsss


};

I try overwrite the value with this:

const temprss = require('../../temp'); 
temprss.lastrsss = "https://something.com";

It works, but same time it doesn't. I think it saves in memory or I don't know. It doesn't save in temp.js. How can I do that it will save in temp.js?

1
  • 1
    It won't; it's local to temp.js, that's the point of modules. You could create a function in temp used to set an internal variable, though. Commented May 23, 2018 at 14:25

2 Answers 2

3

There are a couple ways to handle this. A nice clean one is to define a getter and setter:

temp.js

lastrsss = "hello"

module.exports = {
    get lastrsss() {
        return lastrsss
    },
    set lastrsss(val){
        lastrsss = val
    }
}

Now you can use them just like regular properties:

let tempres = require('./test2.js')

console.log(tempres.lastrsss)  // hello
tempres.lastrsss = "goodbye"
console.log(tempres.lastrsss)  // goodbye
Sign up to request clarification or add additional context in comments.

Comments

0

Export a function to create and set a value in the lastrsss.

Try something like this:

function setLastrsss(value) {
    let lastrsss = value;
    return lastrsss;
}

module.exports = {
   setLastrsss;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.