0

I would like to find the best way to access function variables that are being used as parameters in other functions in another module. The parsefile.js is a Node.js script that is exported as package module and two functions. getfirst and getsecond need to access the variables that are passed from index.js like 'a', 'b' from parsefile('a', 'b', 'c'). Other than using global, do we have another way to do it?

// index.js from some application
const parsefile = require('./parsefile')
parsefile('a', 'b', 'c')


//parsefile.js exports about package module
function getfirst() {
  if (global.f && global.s) {
    return `i have totally 2 arguments: ${global.f}///${global.s}`
  }
  return `first arguments is ${global.f}`
}

function getsecond() {
  return `second arguments is ${global.s}`
}

module.exports = (...args) => {
  global.f = args[0];
  global.s = args[1];
  Promise.all([getfirst(), getsecond()]).then(([first, second]) => {
    console.log(`return from getfirst: ${first}`);
    console.log(`return from getsecond: ${second}`);
  });
}
jacobcan118
  • 7,797
  • 12
  • 50
  • 95

1 Answers1

0

No, don't use global variables! Just pass on the arguments your parsefile function gets via parameters to the functions you are calling:

function getfirst(f, s) {
  if (f && s) {
    return `i have totally 2 arguments: ${f}///${s}`;
  }
  return `first arguments is ${global.f}`;
}

function getsecond(s) {
  return `second arguments is ${s}`
}

module.exports = (f, s) => {
  Promise.all([
    getfirst(f, s),
    getsecond(s)
  ]).then(([first, second]) => {
    console.log(`return from getfirst: ${first}`);
    console.log(`return from getsecond: ${second}`);
  });
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375