Home > other >  Possible to share global variable between two functions without a file?
Possible to share global variable between two functions without a file?

Time:12-14

With the below code, I get

{ test1: 'aaa', test2: 'bbb' }

which is what I want. Ie. being able to have a global variable between t2.js and t3.js.

In this PoC is t3() only called once, but in the real case, if will be ~100 instances of t3() that never ends, because they collect data in an infinite loop. t2.js won't need to modify c.

Question

Is it possible to be the same, but without a third file (t1.js in this case)?

t1.js

module.exports = {};

t2.js

const express = require('express');
const app = express();

let c = require('./t1');
const t3 = require('./t3');

c.test1 = "aaa";
t3();
console.log(c);

app.get('/test.json', (req, res) => {
  res.send(JSON.stringify(c, null, 2));
});    

app.listen(1900, () => {});

t3.js

let c = require('./t1');
module.exports = () => {
  c.test2 = "bbb";
};

CodePudding user response:

It looks like it'd be simple enough to create an object in the entry point, then pass it around:

const express = require('express');
const app = express();

const t3 = require('./t3');

const records = {
  test1: "aaa",
};
t3(records);
console.log(records);

app.get('/test.json', (req, res) => {
  res.send(JSON.stringify(records, null, 2));
});    

app.listen(1900, () => {});
module.exports = (records) => {
  records.test2 = "bbb";
};

Note that neither in this code, nor in your original code, global variables are being used (except, I suppose, for require).

  • Related