Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables for node.js standard modules?

I know that global variables are bad.

But if I am using node's module "util" in 40 files in my framework, isn't it better to just declare it as a global variable like:

util = require('util'); 

in the index.js file instead of writing that line in 40 files?

Cause I often use the same 5-10 modules in each file, that would save a lot of time instead of copy paste all the time.

Isn't DRY good in this case?

like image 423
ajsie Avatar asked Nov 10 '10 02:11

ajsie


People also ask

What are the global variables in NodeJS?

Global variables are variables that can be declared with a value, and which can be accessed anywhere in a program. The scope of global variables is not limited to the function scope or any particular JavaScript file. It can be declared at one place and then used in multiple places.

Why global variables are bad NodeJS?

Global variables are considered an anti-pattern in almost any programming language because they make it very hard to follow and debug code. When you browse the code, you never know which function sets or uses a global variable.

Are global variables shared between modules?

Can I have a shared global variable across different files? As we discussed, the global variable is unique to its own module.

What is module global variable?

A global variable is a variable which is accessible in multiple scopes. In Python, it is better to use a single module to hold all the global variables you want to use and whenever you want to use them, just import this module, and then you can modify that and it will be visible in other modules that do the same.


1 Answers

You could just have a common module.

common.js:

Common = {   util: require('util'),   fs:   require('fs'),   path: require('path') };  module.exports = Common; 

app.js:

var Common = require('./common.js'); console.log(Common.util.inspect(Common)); 
like image 80
Robin Duckett Avatar answered Sep 20 '22 17:09

Robin Duckett