Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda