Overwriting a variable in another file using nodejs

Viewed 44

I have a business scenario which is equivalent to below tricky situation. Hence putting this problem across in a simple way as below.

File1.ts
import * from 'something';
export const var1="value of var1";

//lets say we have a variable 'x' and this needs to be exported too. However value of x is still unknown.
export const x;
File2.ts
import * from 'something';
//set the value of 'x' in File1.ts as 5
File3.ts
import * from 'something'
//I should be able to get the value of 'x' from File1.ts. But it should be equal to the value set by File2.ts which is 5

As mentioned above, I should be able to set the value of x from somewhere (in this case, File2.ts) and everytime I use 'x' from File1.ts, be it in File3.ts or any other file, the value of 'x' should be 5 (set from File2.ts)

1 Answers

File1.ts

var x = 99 //some unknow value

function setValueOfX(value){
  x = value
}

function getValueOfX(){
  return x
}

module.exports = {
  setValueOfX,
  getValueOfX,
}

File2.ts

const File1 = require('./File1.ts')

File1.setValueOfX(5) /// you can set the value of x using the function

File3.ts

const File1 = require('./File1.ts')

console.log(File1.getValueOfX()) /// you can get value of x by using .getValueOfX function

Related