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

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

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 Relatório

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 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