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

261
Views
How to call a function dynamically in Node.js

For web browser I can do like this.

function action(){
    GLOBAL_VAR = 3
}

let GLOBAL_VAR = 0
let funcName = 'action'

window[funcName]()

console.log(GLOBAL_VAR)

How I can do this for Node.js inside a module?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'm not sure what your use case is, but doing this practice in a NodeJS environment is even worse practice than using globals in the browser, since atleast with browser specific code the namespace is distinct to the client's machine, but with NodeJS the global variable is stored in the Server memory, accessible to every request potentially.

You might unwittingly create race conditions and a bunch of problems-- maybe even ddoss your own server if you're continually adding data to the global object since it will eat up your heap memory.

You could use global constants, but having routes modify NodeJS globals seems a bit sketch.

If you insist, you would just use the "global" variable name that's accessible anywhere in your NodeJS Express app.

global.globalString = "This can be accessed anywhere!";

More defined example, index.js:

 const express = require("express");
 const app = express();
 const globals = require('./globals');
 const PORT = 3000;
 
 //set the global var
 global.var = 0;
 global.action = function() {
  console.log('running action');
  return global.var = 3;
 }
 
 app.use('/globals', globals);
 
 app.get('/', (req, res) => {
  res.send("home route");
 })
 
 app.listen(PORT, () => {
  console.log("app running on port: ", PORT);
  console.log('global var: ', global.var);
 })

Then in your routing file,

globals.js:

 const express = require('express');
 const router = express.Router();
 
 router.get('/', function(req, res){
  const action = 'action';
  global[action]();
  res.send('global route')
 });
 module.exports = router;

So yeah, just be sure to set the function and initial variable to the global object in your main app file first before you can use them in your routes. I'd still advise against this.

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!