Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda