Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
nodejs file2 access and assign value to a variable from file1 and once value is assigned value can use back in file1

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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());

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!