Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda