For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentWhat Are Node JS Global Variables?

What Are Node JS Global Variables?

Published
24th Apr, 2024
Views
view count loader
Read it in
10 Mins
In this article
    What Are Node JS Global Variables?

    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 in Full 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?

    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 Built-in Globals in Node.js?

    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 Built-in Globals in Node.js?

    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 out Course 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>node
    Welcome to Node.js v12.18.2.
    Type ".help" for more information.
    > console.log("global objects")
    global objects

    What Are Built-in Globals in Node.js?

    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 Built-in Globals in Node.js?

    Command - 

    C:\Users\jayav>node
    Welcome 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 Built-in Globals in Node.js?
    • 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 -

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

    Output -

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

    What Are Built-in Globals in Node.js?

    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 Built-in Globals in Node.js?

    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.js
    var msg = require('./messages.js');
    console.log(msg);
    C:\> node app.js
    Hello World

    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 seconds
     setTimeout(sayHello, 3000);

    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 seconds
    var t = setTimeout(printHello, 2000);
    // Now clear the timer
    clearTimeout(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.

    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 seconds
    setInterval(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.js
    Hello, World!
    Hello, World!
    Hello, World!
    Hello, World!

    clearInterval(t) - 

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

    var time = 0
    function sayHello() {
        time = time + 1
        console.log( time + " seconds have elapsed");
    
        if(time > 20) {
            clearInterval(timer)
        }
     }  
     // Call the sayHello function every 3 seconds
     timer = 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.

    Profile

    Sachin Bhatnagar

    Blog Author

    Sachin Bhatnagar is an experienced education professional with 20+ years of expertise in Media & Entertainment and Web Technologies. Currently, as the Program Director - Full-Stack at KnowledgeHut, he excels in curriculum development, hands-on training, and strategic deployment of industry-centric educational programs. His online training programs on have attracted over 25,000 learners since 2014. He actively contributes to the development of full-stack training products, leveraging KnowledgeHut's advanced learning platform. Collaborating with organizational leaders, he ensures the success of these programs and has created several technology programs prominently featured in KnowledgeHut's course offerings.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon