0

Is it a good idea to add properties to Node's global object? Searches for this lead me to a discussion of global variables in Node, and frankly I can't find much about the global object for some reason.

From my understanding, global in Node is analogous to the window object that's used in the conventional JS environment, and mutating that is generally frowned upon.

I ask because I'm using Electron whose docs list all sorts of examples that use global, and they even provide an API that lets us set/get global properties from other processes.

From a recent code review, my team was asked to replace the use of global with our own Node module so to avoid overwriting important global attributes set by Node/Electron/3rd party resources.

This seems like a good idea, but why then does Electron recommend the use of global? Why is that the paradigm?


Taking a closer look at the examples, it looks like they recommend only adding one property to the global (sharedObject), so this isn't as bad as I thought, but is this good enough, or should I really take the time to create a separate Node module?

Perhaps this is an opinion-based question.

pushkin
  • 9,575
  • 15
  • 51
  • 95
  • The practice of adding a single property to the global scope is quite common. It's called the "revealing module pattern" and the object is referred to as a _namespace_. In Node.js this is less common due to the existence of the module API, but for electron, there were probably some design challenges with cyclical references that would otherwise lead to very awkward module structures to avoid errors with cyclical module dependencies. That's my guess, anyway. – Patrick Roberts Feb 20 '18 at 22:06
  • if you could avoid patching global, that'd be better in general. I think question should be asked in opposite, what cases you _should require_ to patch global? about 90% cases you won't need it anyway. – OJ Kwon Feb 21 '18 at 00:31

0 Answers0