Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - How to declare global variables on node.js

How to declare some custom variables globally?

Usage Example

import './logger'; // custom module: Global logger is initialized. (using winston)

log.info('This is custom global logger.'); // access to log variable globally.
like image 574
Kunie Avatar asked Nov 24 '25 13:11

Kunie


1 Answers

In TypeScript, declare global block's are used to describe to add a variable to global namespace or declare a global variables.

Node.js

import * as io from 'socket.io';

declare global {
  namespace NodeJS {
    interface Global {
      SocketServer: io.Server
    }
  }
}

global.SocketServer = io.default();

Note : Global variables are fine in some cases, even with multiple processes. Its recommended / commonly used when we have want to store a constant values, example some email ids during failures ex. global.support_email = "[email protected]"

Ref might be duplicate:

How to use global variable in node.js?

How to create writable global variable in node.js typescript (Using Typescript)

How to use global variable in node.js?

like image 75
Senthil Avatar answered Nov 27 '25 15:11

Senthil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!