Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Possible to share global variable between two functions without a file?

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";
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!