What Are Node JS Global Variables & How to Use It? (2024)

Node js has a number of inbuilt globals like any other javascript framework. These inbuilt globals help us to develop any kind of new feature without writing much logic in our program. By using these built-in globals, we just need to call these predefined functions with proper parameters. In this blog, we shall explore inbuilt global variables in Node.js, and how we can declare and use them in our applications. For more information on web development, enroll inFull Stack Development Bootcamp.

What are Global Variables in NodeJS?

Global variables in NodeJS 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 in one place and then used in multiple places.

How to Declare and Use a Global Variable in Node.js?

Global Variables can be declared by using global objects in NodeJS. The following is an example where the title, which is a variable, is used as a global variable:

Example:

File name – app.js
global.title = "Global Variable Declaration";

The above statement tells us the way to declare a global variable in Node.js. Now, let’s discuss how to use global variables.

What Are Node JS Global Variables & How to Use It? (1)

A global variable can be used inside another module of our node app like this:

route.js - Add below lines to route.js file

var logger = require('./app');console.log(title); // output – “Global Variable Declaration”

Then go to the path and run node route.js. You will see the output.

Let’s discuss some of the practical use cases of global variables in Node.js:

Some more declaration statements

a = 10;GLOBAL.a = 10;global.a = 10;

All the above commands give the same actions, just with different syntax.

In the screenshot below, I have placed my files on the desktop and run the below command after going to the path:

What Are Node JS Global Variables & How to Use It? (2)

Practical Use Cases for Global Variables in Node.js

So far, we have built a basic understanding of Node.js global variables and their ways of declarations. We will now understand some of the practical use cases of global variables in real-world programming.

Before creating global variables, there are a few important points we need to keep in mind:

Global variables can be accessed globally through any function and JavaScript file so it can cause concurrency issues if more than one file is accessing it at a time. Another problem we need to keep in mind is that global variables can occupy the space in memory till the program run so sometimes it impacts the memory utilization as well.

Let us discuss one example of a global node.js variable that is inbuilt and used by every programmer in code.

Sample Code:

console.log("Hello World!");process.env.PORT = 3000;setInterval({ console.log("2 seconds passed.");}, 2000);

In the above sample code first statement console.log (“Hello World!”) is a global variable that is used by every developer to print any statement in the console of the browser.

The next statement process object is also a global variable that provides information about the current running Node process and therefore should be available from any file without having to require it.

Similarly, set Interval is another function that you may have seen before if you ever had reason to delay an operation before executing it.

We are going to discuss the most important and commonly used global objects one by one in the next section of this article. Before proceeding forward, check outCourse for Developer.

Common Global Objects in Node.js

1. global

The global namespace object. 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. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.

2. Console 

This global object in Node.js we already discussed in the above code sample is used for printing to stdout and stderr.

Command to run on cmd terminal:

C:\Users\jayav>nodeWelcome to Node.js v12.18.2.Type ".help" for more information.> console.log("global objects")global objects

What Are Node JS Global Variables & How to Use It? (3)

3. Process

It is an inbuilt global object in NodeJS that is an instance of an Event Emitter used to get information on the current process. It can also be accessed using require () explicitly.

4. Class: Buffer

Class buffer is also one of the built-in globals which are used mainly for binary data.

Example: If node js is installed in your system open cmd and run the below commands as per screenshot you will see the same output.

What Are Node JS Global Variables & How to Use It? (4)

Command:

C:\Users\jayav>nodeWelcome to Node.js v12.18.2.Type ".help" for more information.> const buffer = new Buffer.alloc(5,"abcde")undefined> console.log(buffer)<Buffer 61 62 63 64 65>undefined

5. Node.js require() Module

Node.js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require() is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.

Syntax:

require(‘module_name’)
require.resolve() require.resolve(request[, options])
  • request: It is of type string. Contains the path of the module to resolve
  • options: It is of type object. Contains the path to resolve module location from.

require.resolve.paths(request)

  • request: It is of type string. Contains the module path whose lookup paths are being retrieved.

Example:

const config = require('/path/to/file');

The above code has a required function where path parameter we need to pass and in the background below process will be executed.

  • Resolving and Loading: when node js is installed in computer system it will install with set of folder structure. Among all the folders node_modules is one of the folder where all inbuilt modules will be available. During any code execution when it requires node module first it will check in node_module folder this process is called Resolving and Loading.
  • Wrapping: When Node.js module will get loaded from node_module folder then its funtions can be used. This process is called wrapping.

module2.js

// Caching const mod = require('./module1.js') module1.js console.log(require("module").wrapper); [ '(function (exports, require, module, __filename, __dirname) { ', '\n});' ]
  • Execution:Modules exported using require () method will be executed in this step and will help us to export the module which is resolved in the above step. The below diagram is a representation of require () where module one depends on module two and in return it is exported from module two to module one.

    What Are Node JS Global Variables & How to Use It? (5)

  • Caching:Caching is the most important step in require() as it improves the performance of retrieval of the module. The first time when module loads it takes time to load next time when again we require to load this module it will be loaded through caching which is stored in browser history.

Let's take an example to understand caching
module1.js

console.log("Hello"); module.exports = ()=> console.log("node js sample code !!");

module2.js

// Caching const mod = require('./module1.js'); mod(); mod(); mod();

Output:

// Cachingconst mod = require('./module1.js'); mod(); mod(); mod(); 

Output:

Hello node js sample code !! node js sample code !! node js sample code !!

What Are Node JS Global Variables & How to Use It? (6)

6. filename  

The __filename in the Node.js returns the filename of the code which is executed. It gives the absolute path of the code file. The following approach covers how to implement __filename in the NodeJS project.

Create a JavaScript file index.js and write down the following code:

// Node.js code to demonstrate the absolute.// file name of the current Module. console.log("Filename of the current file is: ", __filename); Run the index.js file using the following command: node index.js

Output:

Filename of the current file is:

 C:\Users\Jayav\Desktop\node_func\app.js

7. dirname 

__dirname in a node script returns the path of the folder where the current JavaScript file resides.

// Node.js program to demonstrate the // methods to display directory // Include path module var path = require("path"); // Methods to display directory console.log("__dirname: ", __dirname);

Steps to Run:

  • Open notepad editor and paste the following code and save it with .js extension. For example: index.js
  • Next, open a command prompt and move to the directory where code exists.
  • Type node index.js command to run the code.

Output:

What Are Node JS Global Variables & How to Use It? (7)

8. module  

Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application.

Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate .js file under a separate folder.

Node.js includes three types of modules: Core Modules ,Local Modules, and Third Party Modules.

Example: Load and Use Core http Module.

var http = require('http');http.createServer(function (req, res) {res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Welcome to this page!'); res.end();}).listen(3000);

In the above example, the require() function returns an object because the Http module returns its functionality as an object. The function http.createServer() method will be executed when someone tries to access the computer on port 3000. The res.writeHead() method is the status code where 200 means it is OK, while the second argument is an object containing the response headers.

9. exports 

The module.exports is a special object which is included in every JavaScript file in the Node.js application by default. The module is a variable that represents the current module, and exports is an object that will be exposed as a module.

Example: file name messages.js

module.exports = 'Hello world';

Now, import this message module and use it as shown below.

app.jsvar msg = require('./messages.js');console.log(msg);C:\> node app.jsHello World

A. etTimeout(cb, ms):

This is a global function used to run a callback at given interval

cb – the function to execute
ms – the number of miliseconds to delay

For example, the code below executes the function sayHello after 3 seconds. So the text ‘Welcome to Node.js’ is displayed after 3 seconds. I recommend you try it and see how it works.

function sayHello() { console.log( "Hello my friend!");} // Call the sayHello function every 3 secondssetTimeout(sayHello, 3000);

B. clearTimeout(t) :

The clearTimeout(t) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by the setTimeout() function.

Create a js file named main.js with the following code -

function printHello() { console.log( "Hello, World!");}// Now call above function after 2 secondsvar t = setTimeout(printHello, 2000);// Now clear the timerclearTimeout(t);

Run the main.js to see the result -

$ node main.js

Once you run above program through coomand prompt you will notice that there will be no output as clearTimeout(t) will clear the output.

C. setInterval(cb, ms) :

setInterval(cb,ms)- is a global inbuilt funtion in node js and it accepts two arguments one is cb - which means callback and ms - meaning time in milliseconds.

Create a js file named main.js with the following code -

 function printHello() { console.log( "Hello, World!");}// Now call above function after 2 secondssetInterval(printHello, 2000);

Now run the main.js to see the result -

$ node main.js

The above program will execute printHello() after every 2 seconds

$node main.jsHello, World!Hello, World!Hello, World!Hello, World!

D. clearInterval(t) :

This in-built global function takes t as time parameter where time function gets called in every t seconds.

var time = 0function sayHello() { time = time + 1 console.log( time + " seconds have elapsed"); if(time > 20) { clearInterval(timer) }} // Call the sayHello function every 3 secondstimer = setInterval(sayHello, 1000);

In the above block of code, clearInterval is get called for each passing time till it reached threshold 20 seconds and setInternal() funtion get called for specific time intervals.

Looking to kickstart your coding journey? Join our Python course for beginners with certificate! Learn the language that powers tech giants and opens doors to endless opportunities. Start coding today and unlock your full potential. Enroll now!

Globals Make Apps Better

We've seen how built-in globals have several different forms and use. They enable web developers to enhance the functioning of a web application, through features like a timer, for which we use clearinterval or setInterval or clearTimeout in build globals. Built in globals are native to Node and can be used anywhere throughout the application like global variables used in other applications.

Frequently Asked Questions (FAQs)

1. What isalternativeto global variables in NodeJS?

In Node.js, alternatives to global variables include using module exports to share variables and functions between modules, using the required function to import them. Another approach is to use dependency injection, where you pass dependencies explicitly into functions or objects, enhancing modularity and testability. Additionally, the use of closures or the global object selectively can help manage shared state in a controlled manner.

2. What is the difference between global and local node JS?

"Global Node.js" typically refers to packages and tools installed globally on your system, making them accessible from any project via the command line. These are installed using the -g flag withnpm. "Local Node.js" refers to packages installed within a specific project directory, stored in thenode_modulesfolder, and accessible only within that project. Local installations are managed without the -g flag and are specified in the project'spackage.json.

3. Can I create custom global variables in Node.js?

Yes, you can create custom global variables in Node.js by attaching them to the global object. For example,global.myVariable= "someValue"; will makemyVariableaccessible throughout the application. However, this practice isgenerally discouragedbecause it can lead to unpredictable behavior and makes the code harder tomaintainand debug due to potential naming conflicts and implicit dependencies.

4. Are there any best practices for using global variables in Node.js?

Best practices for using global variables in Node.js include minimizing their use to avoid potential conflicts andmaintainmodularity. Ifglobalsare necessary, use a clear naming convention to reduce conflicts and ensure they are well-documented. Prefer using configuration files or environment variables for application-wide settings. Encapsulate global state within modules orclasses, andconsider using patterns like dependency injection to manage dependencies explicitly.

What Are Node JS Global Variables & How to Use It? (2024)
Top Articles
SSI vs. SSDI: What Are These Benefits and How Do They Differ?
What to Own When the Dollar Collapses: Fiat Currency Collapse | 2024 Edition
Automated refuse, recycling for most residences; schedule announced | Lehigh Valley Press
Using GPT for translation: How to get the best outcomes
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
30 Insanely Useful Websites You Probably Don't Know About
From Algeria to Uzbekistan-These Are the Top Baby Names Around the World
Wild Smile Stapleton
Puretalkusa.com/Amac
Concacaf Wiki
Programmieren (kinder)leicht gemacht – mit Scratch! - fobizz
House Of Budz Michigan
Quest Beyondtrustcloud.com
Convert 2024.33 Usd
Sizewise Stat Login
Accident On The 210 Freeway Today
Egizi Funeral Home Turnersville Nj
Red Cedar Farms Goldendoodle
Bocca Richboro
Craigslist Dubuque Iowa Pets
1979 Ford F350 For Sale Craigslist
Claio Rotisserie Menu
Tom Thumb Direct2Hr
Srjc.book Store
In hunt for cartel hitmen, Texas Ranger's biggest obstacle may be the border itself (2024)
Gt7 Roadster Shop Rampage Engine Swap
Fastpitch Softball Pitching Tips for Beginners Part 1 | STACK
Slv Fed Routing Number
School Tool / School Tool Parent Portal
Retire Early Wsbtv.com Free Book
Acadis Portal Missouri
Uc Santa Cruz Events
B.C. lightkeepers' jobs in jeopardy as coast guard plans to automate 2 stations
Walmart Car Service Near Me
Silicone Spray Advance Auto
Pike County Buy Sale And Trade
Autozone Battery Hold Down
Quaally.shop
Gabrielle Abbate Obituary
Arch Aplin Iii Felony
Greg Steube Height
Booknet.com Contract Marriage 2
877-552-2666
Market Place Tulsa Ok
Plasma Donation Greensburg Pa
Guy Ritchie's The Covenant Showtimes Near Look Cinemas Redlands
Zits Comic Arcamax
The Plug Las Vegas Dispensary
Renfield Showtimes Near Regal The Loop & Rpx
Affidea ExpressCare - Affidea Ireland
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 5346

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.