Home > Software engineering >  nodejs file2 access and assign value to a variable from file1 and once value is assigned value can u
nodejs file2 access and assign value to a variable from file1 and once value is assigned value can u

Time:01-02

I am creating a program in nodejs. I have a file1.js and file2.js file1.js has a variable which is exported and to get assign value from file2.js so this value can be used here in file1.js.

file1.js

// user given value
let value;

// exporting 
module.exports  = value

value I want to use here in file1.js once access and assigned from file2.js

file2.js

const value = require("./file1");

// Give a value
value = 5

but its not working what should I do I tried to search example but not able to understand also I don't want to create this variable in file2.js because I don't want to export from file2.js.

help will be much appreciated. Thanks

CodePudding user response:

It won't work because you are using const, however, you should use let here.

let value = require("./file1");

// Give a value
value = 5;
console.log(value); // 5

Node imports are always Singleton and have the caching mechanism. So, this value will be shared in all the imports.

CodePudding user response:

file2.js

let value;

const setValue = (v) => {
  value = v;
};

const getValue = () => {
  return value;
};

module.exports = { setValue, getValue };

file1.js

const { setValue, getValue } = require("./file1");

setValue(5);
console.log(getValue());

  • Related