Home > other >  How to send a variable inside of a function to be accessed in another file in Nodejs
How to send a variable inside of a function to be accessed in another file in Nodejs

Time:09-24

I have 2 files named test.js and test2.js , I write a function in test1.js which stores a value in a variable from the function call, but I am unable to access that value in the variable in test2.js file. Whenever I try to do that, it shows undefined.

Can someone please guide me through the same

here are what my 2 files look like

let det='';
let fine='';
async function init(key)
{
    try{

        det=pkey;
        console.log(pkey);
        fine = uuidv4();
        console.log(fine);
        
    }
    catch(error){
        console.error(error);
    }

}

Now I want to access both det and fine in another file named test2.js , where I use axios


async function getAll(){
    try{
            const response=await axiosClient.get('/shoes',{ headers: {"key" : `${det}`,"sess":`${fine}`}});
            console.log(response.data);
    }
    catch(error){
        console.error(error);
    }
   
    
}
module.exports.getAll=getAll;

CodePudding user response:

So it is technically feasible but maybe not recommended.

# file 1
let test1 = 0;
function init1 {test1 = 2;};
init1();
export function getTest1() {return test1};
# file 2
import { getTest1 } from './file1';
function logTest1() {
  console.log(getTest1());
}

CodePudding user response:

If you declare the variable in a global scope first in the initial script and assign it (without redeclaring) you can achieve this pretty simply. Perhaps show your code so can see a bit better what your issue is?

//test1.js
let test = 'test';
function changeTest(change = null) {
    test = change || test;
}

//test2.js
(() => {
    console.log(`GLOBAL VARIABLE: ${test}`); // test is 'test'
    changeTest('changed');
    console.log(`AFTER CHANGE: ${test}`); // test is 'changed'
})();

See https://www.w3schools.com/js/js_scope.asp for more information on JS scope management

  • Related