Search code examples
javascriptnode.jsgetter-setteraccessor

Is it possible to set module.exports as a setter/getter javascript?


In file a.js

// a.js
let a = 1

Object.defineProperty(module, "exports", {
  get() {
    return a
  },
  set(v) {
    a += 1
  },
  enumerable: true,
  configurable: true,
})

In file b.js

// b.js
const a = require("./a")
console.log(a) // 1
a = 2 // a should now be 3
// Throws "Uncaught TypeError: Assignment to constant variable."

Is there some way to do this? (use setter on something I require'd)


Solution

  • Yes! But also, No.

    While this technically IS doable, you then run into the issue of not being able to access the setter once it is required, as it will call the Getter and return the value when require()'d. So the getter/setter functionality is Only accessible via the source file, with the getter supplying a response to require.