I am a full-stack Web Application Developer and passionate about exploring cutting edge technologies. I love to write technical blogs.
Read it in 10 Mins
Is by Doing
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.
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.
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.
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:
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.
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.
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
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.
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.
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
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(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.
- 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.
module2.js
// Caching
const mod = require('./module1.js')
module1.js
console.log(require("module").wrapper);
[
'(function (exports, require, module, __filename, __dirname) { ',
'\n});'
]
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 !!
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
__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:
Output -
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.
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
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);
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)- 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!
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.
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.
Name | Date | Fee | Know more |
---|