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 Overflow
🌐
Node.js
nodejs.org › api › globals.html
Global objects | Node.js v25.8.1 Documentation
You can figure out which version of undici is bundled in your Node.js process reading the process.versions.undici property. You can use a custom dispatcher to dispatch requests passing it in fetch's options object. The dispatcher must be compatible with undici's Dispatcher class. ... It is possible to change the global dispatcher in Node.js by installing undici and using the setGlobalDispatcher() method.
Discussions

Node.js global variables - javascript
I asked here: Does Node.js require inheritance? And I was told that I can set variables to the global scope by leaving out the variable. This does not work for me. That is, the following does not m... More on stackoverflow.com
🌐 stackoverflow.com
Global Variable Node
Using global variables to pass headers down through functions isn’t the best idea. It can lead to bugs, especially with concurrent requests messing up the shared state. It’s usually better to pass data explicitly through function arguments or use context to keep things clean and predictable. Speaking from experience... More on reddit.com
🌐 r/node
15
6
September 5, 2024
How to deal with global variables when modularizing a node.js app?
As much as possible, anything that a function changes should be returned from it rather than modified in place. The purer a function is, the easier it is to test, to reason about, and to compose. Your second best bet if that's impractical is to turn the globals into data attached to the "this" object that your functions are being called as methods on. This still improves your ability to reason about data because it is scoped to a set of functions rather than the whole program. I would caution you against having a giant "context" object that holds all of the mutable globals that you pass around to every function. This is the easiest thing to do when refactoring from a program with lots of globals, but it doesn't actually buy you much over the globals. You're still left with a lot of implicit state that you need to set up before calling each function. More on reddit.com
🌐 r/node
4
1
May 7, 2016
How to set and access global variables in node.js
Set and export those values from a separate file, just import them wherever needed. Imports are cached, meaning the code in that file will be executed just once. More on reddit.com
🌐 r/node
3
0
June 4, 2023
🌐
Medium
medium.com › @a.kago1988 › global-objects-variables-and-methods-in-javascript-and-node-js-f6bffc74e792
Built-In Objects, Variables, and Methods. What the Node.js Runtime Provides | by Andreas 🎧 Kagoshima | Medium
1 week ago - __filename: This variable holds the full path to the current module (file). It’s easy to assume that variables like __dirname and __filename are global because they seem available everywhere within a Node.js module.
🌐
Stack Abuse
stackabuse.com › using-global-variables-in-node-js
Using Global Variables in Node.js
July 8, 2024 - The difference between a regular variable and a global variable comes down to their scope. When you create a variable in a JavaScript file, that variable only exists in the scope that it was declared in. Now what do I mean by this? In the code below, you can see an example of two different variables with different scopes. // Scope.js let fileScope = "Can be accessed anywhere in the file"; function doSomething() { let localScope = "Can only be accessed inside this function"; fileScope = "Can be accessed in the function too!"; } // This will result in an error because the variable does not exist // outside the function.
Top answer
1 of 7
242

You can use global like so:

global._ = require('underscore')
2 of 7
221

In Node.js, you can set global variables via the "global" or "GLOBAL" object:

GLOBAL._ = require('underscore'); // But you "shouldn't" do this! (see note below)

or more usefully...

GLOBAL.window = GLOBAL;  // Like in the browser

From the Node.js source, you can see that these are aliased to each other:

node-v0.6.6/src/node.js:
28:     global = this;
128:    global.GLOBAL = global;

In the code above, "this" is the global context. With the CommonJS module system (which Node.js uses), the "this" object inside of a module (i.e., "your code") is not the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.

console.log("\nTHIS:");
console.log(this);
console.log("\nGLOBAL:");
console.log(global);

/* Outputs ...

THIS:
{}

GLOBAL:
{ ArrayBuffer: [Function: ArrayBuffer],
  Int8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Uint8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Int16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Uint16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Int32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Uint32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float64Array: { [Function] BYTES_PER_ELEMENT: 8 },
  DataView: [Function: DataView],
  global: [Circular],
  process:
   { EventEmitter: [Function: EventEmitter],
     title: 'node',
     assert: [Function],
     version: 'v0.6.5',
     _tickCallback: [Function],
     moduleLoadList:
      [ 'Binding evals',
        'Binding natives',
        'NativeModule events',
        'NativeModule buffer',
        'Binding buffer',
        'NativeModule assert',
        'NativeModule util',
        'NativeModule path',
        'NativeModule module',
        'NativeModule fs',
        'Binding fs',
        'Binding constants',
        'NativeModule stream',
        'NativeModule console',
        'Binding tty_wrap',
        'NativeModule tty',
        'NativeModule net',
        'NativeModule timers',
        'Binding timer_wrap',
        'NativeModule _linklist' ],
     versions:
      { node: '0.6.5',
        v8: '3.6.6.11',
        ares: '1.7.5-DEV',
        uv: '0.6',
        openssl: '0.9.8n' },
     nextTick: [Function],
     stdout: [Getter],
     arch: 'x64',
     stderr: [Getter],
     platform: 'darwin',
     argv: [ 'node', '/workspace/zd/zgap/darwin-js/index.js' ],
     stdin: [Getter],
     env:
      { TERM_PROGRAM: 'iTerm.app',
        'COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET': '/tmp/launch-nNl1vo/ServiceProcessSocket',
        TERM: 'xterm',
        SHELL: '/bin/bash',
        TMPDIR: '/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/',
        Apple_PubSub_Socket_Render: '/tmp/launch-9Ga0PT/Render',
        USER: 'ddopson',
        COMMAND_MODE: 'unix2003',
        SSH_AUTH_SOCK: '/tmp/launch-sD905b/Listeners',
        __CF_USER_TEXT_ENCODING: '0x12D732E7:0:0',
        PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11/bin',
        PWD: '/workspace/zd/zgap/darwin-js',
        LANG: 'en_US.UTF-8',
        ITERM_PROFILE: 'Default',
        SHLVL: '1',
        COLORFGBG: '7;0',
        HOME: '/Users/ddopson',
        ITERM_SESSION_ID: 'w0t0p0',
        LOGNAME: 'ddopson',
        DISPLAY: '/tmp/launch-l9RQXI/org.x:0',
        OLDPWD: '/workspace/zd/zgap/darwin-js/external',
        _: './index.js' },
     openStdin: [Function],
     exit: [Function],
     pid: 10321,
     features:
      { debug: false,
        uv: true,
        ipv6: true,
        tls_npn: false,
        tls_sni: true,
        tls: true },
     kill: [Function],
     execPath: '/usr/local/bin/node',
     addListener: [Function],
     _needTickCallback: [Function],
     on: [Function],
     removeListener: [Function],
     reallyExit: [Function],
     chdir: [Function],
     debug: [Function],
     error: [Function],
     cwd: [Function],
     watchFile: [Function],
     umask: [Function],
     getuid: [Function],
     unwatchFile: [Function],
     mixin: [Function],
     setuid: [Function],
     setgid: [Function],
     createChildProcess: [Function],
     getgid: [Function],
     inherits: [Function],
     _kill: [Function],
     _byteLength: [Function],
     mainModule:
      { id: '.',
        exports: {},
        parent: null,
        filename: '/workspace/zd/zgap/darwin-js/index.js',
        loaded: false,
        exited: false,
        children: [],
        paths: [Object] },
     _debugProcess: [Function],
     dlopen: [Function],
     uptime: [Function],
     memoryUsage: [Function],
     uvCounters: [Function],
     binding: [Function] },
  GLOBAL: [Circular],
  root: [Circular],
  Buffer:
   { [Function: Buffer]
     poolSize: 8192,
     isBuffer: [Function: isBuffer],
     byteLength: [Function],
     _charsWritten: 8 },
  setTimeout: [Function],
  setInterval: [Function],
  clearTimeout: [Function],
  clearInterval: [Function],
  console: [Getter],
  window: [Circular],
  navigator: {} }
*/

** Note: regarding setting "GLOBAL._", in general you should just do var _ = require('underscore');. Yes, you do that in every single file that uses Underscore.js, just like how in Java you do import com.foo.bar;. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. It is mildly annoying, but a good thing. .... That's the preaching.

There is an exception to every rule. I have had precisely exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "configuration" files which were basically JSON, but were "written in JavaScript" to allow a bit more flexibility. Such configuration files had no 'require' statements, but I wanted them to have access to Underscore.js (the entire system was predicated on Underscore.js and Underscore.js templates), so before evaluating the "configuration", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "I get tired of typing 'require', so I want to break with the convention".

🌐
Node.js
nodejs.org › download › release › v14.16.1 › docs › api › globals.html
Global objects | Node.js v14.16.1 Documentation
In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different.
🌐
Reactgo
reactgo.com › home › how to declare a global variable in node.js
How to declare a global variable in Node.js | Reactgo
February 15, 2023 - In this tutorial, we are going to learn about how to declare and use global variables in Node. In Node.js, each module has its own scope the…
Find elsewhere
🌐
Node.js
nodejs.org › download › release › v12.13.0 › docs › api › globals.html
Global Objects | Node.js v12.13.0 Documentation
In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript technology tutorial › node.js global variable
Node.js Global Variable | How Global Variable Work in Node.js?
March 29, 2023 - This is the global object, and some variables and functions are globally defined under this. So, for example, we have seen a console.log() statement. But in node, we have a different scenario. Node is a server-side JavaScript run environment. That means the window object is browser-specific. So it will not help with node js.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
KnowledgeHut
knowledgehut.com › home › blog › software development › global objects in node js: how they can make or break your code?
Don't Ship Code Without Knowing Global Objects in Node js!
July 7, 2025 - By referencing these variables through process.env, you can configure your application based on the environment in which it is running. This approach ensures security and is ideal for production environments. Global objects, like process, play a key role in error handling in Node.js applications. For example, process.on('uncaughtException') allows you to catch unhandled exceptions, preventing the application from crashing.
🌐
W3Resource
w3resource.com › node.js › nodejs-global-object.php
Node.js : Global Objects - w3resource
November 13, 2023 - In the following example, 'Node.js' string will print repeatedly in every 300 milliseconds. setInterval(function(){ console.log('Node.js') }, 300); ... The clearInterval() is used to stop a timer that was set with setInterval(). The callback ...
🌐
Speakingjs
speakingjs.com › es5 › ch16.html
Chapter 16. Variables: Scopes, Environments, and Closures
Node.js contains global, which is a Node.js-specific variable. Each module has its own scope in which this points to an object with that scope’s variables.
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › global-variable
Global Variables in JavaScript - Mastering JS
February 2, 2021 - If you're importing uncompiled JavaScript in the browser using <script> tags, global variables are shared between different <script> tags. In other words, different <script> tags share the same global scope. <script type="text/javascript"> const answer = 42; </script> <script type="text/javascript"> console.log(answer); // 42 </script> Things are a little different in Node.js.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Glossary › Global_object
Global object - Glossary - MDN Web Docs - Mozilla
console.log(globalThis === globalThis.globalThis); // true (everywhere) console.log(window === window.window); // true (in a browser) console.log(self === self.self); // true (in a browser or a Web Worker) console.log(frames === frames.frames); // true (in a browser) console.log(global === global.global); // true (in Node.js)
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › node-js-global-objects
NodeJS Global Objects - GeeksforGeeks
January 17, 2026 - Node.js provides a global scope mechanism that allows certain variables and functions to be available across the entire application without explicit imports.
🌐
Node.js
nodejs.org › docs › v0.4.2 › api › globals.html
globals - Node.js Manual & Documentation
The top-level scope is not the global scope; var something inside a Node module will be local to that module. The process object. See the 'process object' section. To require modules. See the 'Modules' section. Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename. An array of search paths for require(). This array can be modified to add custom paths. Example: add a new path to the beginning of the search list
🌐
Readthedocs
node.readthedocs.io › en › latest › api › globals
Globals - node - Read the Docs
In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different.
🌐
Node.js
nodejs.org › docs › latest-v8.x › api › globals.html
Global Objects | Node.js v8.17.0 Documentation
In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different.