user8209141
user8209141

Reputation:

Node.JS Overwrite module export value

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?

Upvotes: 2

Views: 2529

Answers (2)

Mark
Mark

Reputation: 92440

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

Upvotes: 3

Fernando Paz
Fernando Paz

Reputation: 623

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;
}

Upvotes: 0

Related Questions