Most people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
module.exports = new logger(customConfig);
foobar.js
var logger = require('./logger');
logger('barfoo');
If you do want a global variable you can do:
global.logger = new logger(customConfig);
Answer from Pickels on Stack OverflowMost people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
module.exports = new logger(customConfig);
foobar.js
var logger = require('./logger');
logger('barfoo');
If you do want a global variable you can do:
global.logger = new logger(customConfig);
global.myNumber; // Declaration of the global variable - undefined
global.myNumber = 5; // Global variable initialized to value 5.
var myNumberSquared = global.myNumber * global.myNumber; // Using the global variable.
Node.js is different from client Side JavaScript when it comes to global variables. Just because you use the word var at the top of your Node.js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' .
To make something global just put the word global and a dot in front of the variable's name. So if I want company_id to be global I call it global.company_id. But be careful, global.company_id and company_id are the same thing so don't name global variable the same thing as any other variable in any other script - any other script that will be running on your server or any other place within the same code.
Videos
Hi!
I'm working on an API and I need to pass down some header to a low level cache function.
I didn't want to drill this header through many other functions and thought I could do something like we do in React with global context.
How safe and viable it is to declare a global variable on a controller level to be accessed down the line?
Am I being too naive or careless about this approach?
Hey all,
I have been working on an api for the last 2 months and my main index.js page has reached 2000 lines of code. I now need to modularize my application into submodules.
My main problem is I don't know how I will implement global variables into a modularized structure. For objects and arrays, I can just pass them down to my function has an argument since they are passed by reference but for every other datatype, I can't pass them as a reference.
What is the most common way to deal with modularizing a node.js app which has global variables?
EDIT: Specifically, how would you deal with global variables in Koa.js?