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

213
Views
Does require in javascript/nodejs executes same file everytime it is imported in another modules?

Does require() in JavaScript/Node.js executes the same file every time it is imported into other modules?

If yes, how can I have one array in one file and append/update values in it from another JS file? For example, I have an Array in one file and I am updating the Array from multiple files and I want all of them to interact with only the updated array. How can I achieve this?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Modules are cached, if you load them again cached copy is loaded.

https://nodejs.org/api/modules.html#modules_require_cache

Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module. This does not apply to native addons, for which reloading will result in an error.

Adding or replacing entries is also possible. This cache is checked before native modules and if a name matching a native module is added to the cache, no require call is going to receive the native module anymore. Use with care!

You can use https://www.npmjs.com/package/clear-module

const clearModule = require('clear-module');
const myArray = clearModule('./myArray'); // but you need load this everytime to get fresh copy of that array

Instead, you can expose a function from your module to read the array value, so it will fetch a new value always.

myArray.js

const myArray = [1];

const get = () => {
  return myArray;
};

const update = (data) => {
  myArray.push(data);
};

exports.get = get;
exports.update = update;

index.js

const myArray = require('./myArray');

console.log(myArray.get()); // [1]
console.log(myArray.update(2)); // update the value
console.log(myArray.get()); // [1,2]

So now use myArray.get() always to read the value and use myArray.update(data) to update the.

over 4 years ago · Santiago Trujillo 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!