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