Home > Blockchain >  Initiate a value for a exported variable using exported function Node js
Initiate a value for a exported variable using exported function Node js

Time:10-08

I am trying to set a value to an exported variable using an exported function

Please find the code below

module.js

let globalVariable;
let initFunction = (value) => {
    console.log('init Function')
    globalVariable = value;
}
module.exports = {
    initFunction,
    globalVariable
}

app.js

let {globalVariable,initFunction} = require('./module');
initFunction('test');
console.log('globalVariable: ' globalVariable);

When I try to run app.js, I am getting undefined for globalVariable. How to properly set value to this variable?

Please help Thanks in advance

CodePudding user response:

You are replacing globalVariable so the one after update by initFunction is no more the one that you exported. Init function assign a new pointer to globalVariable, do no mutate the string pointed by globalVariable.

You can place the values inside a data structure that, like an object.

let globalVariable = {};
let initFunction = (value) => {
    console.log('init Function')
    globalVariable.a = value;
}
module.exports = {
    initFunction,
    globalVariable
}

app.js

let {globalVariable,initFunction} = require('./module');
initFunction('test');
console.log('globalVariable: ' globalVariable.a);

It depends on what you need to achieve but can be helpfull for you to consider globalThis

  • Related