Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda