Global Variables in Node.js

    0 Votes

Global variables are a set of variables which are available in every file executed through NodeJS without having to import any modules. These global variables perform some important functions which are very useful in various cases. Lets see the use of global variable with the help of a program.

Hello World Application with another file - 2

Create a new directory and open terminal here. Do an npm init to initialize your npm project. Then, like the previous article, create the same two files
  1. index.js - This will contain our JavaScript Code
  2. myTextFile.txt - This will contain our text to display

 

myFolder and move the myTextFile.txt into this folder. So should have a file-folder structure as:

folder structure
Following are the contents of the files
myTextFile.txt
folder structure
index.js
"use strict"; // Enable Strict Mode
const fs = require('fs'); // Import 'fs' module
const path = require('path'); // Import 'fs' module
let readMyText = function() 
{
	let str = fs.readFileSync(path.join("myfolder","./myTest.txt")).tostring(); // Read file from local file system
	console.log(str); //Print the string
};
readMyText();

 

There are some changes in the index.js file. Let us see them one by one. In line 4, we import the path module. Path is a NodeJS core module which helps to concatenate file path irrespective of the operating system. For example, my index.js file’s full path will be:

In LINUX/UNIX style

/home/jibin/Documents/NodeJS/a4acdemics/index.js

In Windows style (just to show the difference)

\home\jibin\Documents\NodeJS\a4acdemics\index.js

Notice that in unix based system, the directories are separated by a Backslash ( / ) whereas in Windows they are separated by Forward Slash ( \ ).

If you write line 7 as :

let str = fs.readFileSync(“/myFolder/myTextFile.txt”).toString();

the program will run in unix based systems but will crash on windows based systems.

The path.join function takes any number of strings and joins them with the appropriate File Separators based on the current operating systems.

path join

Now run this app. So your app is running successfully… But wait..!!!

running app

Try running the same app from a different directory
Woah Woah Woah….!!! What happened?????? It was working fine.

What happens is that when you specify the file path in any function, by default it takes the relative path with respect to the location from where the script is called. If an absolute path is specified then it looks up the absolute path. Absolute path starts with a leading slash.

In simple words: In the first case when script is invoked as:

jibin@jibin-mathews ~/Documents/NodeJS/a4academics $ node index.js

the fs.readFileSync() function looks for the myTextFile.txt in the location

~/Documents/NodeJS/a4academics/myFolder/myTextFile.txt

But in the second case when running as:

jibin@jibin-mathews ~/Documents/NodeJS $ node index.js

the fs.readFileSync() function looks for the myTextFile.txt in the location

~/Documents/NodeJS/myFolder/myTextFile.txt

This file doesn’t exist and hence throws an error.

So how do we fix this problem without knowing the location from where is script is run?

To solve this we use a special variable provided in NodeJS __dirname (There are 2 underscores in the name).

__dirname stores the absolute path of the directory in which the current code is written.
In this case __dirname = ~/Documents/NodeJS/a4academics

Now replace the 7th line by:

let str = fs.readFileSync(path.join(__dirname, ”myFolder”, “myTextFile.txt”)).toString();

and try executing

nodejs script

Now it works. Try executing it from ANY location of your system.

The __dirname variable used here is an example of global variable. Let us have a look at some more useful global variables.

module

Module is a reference to the current module. This means that module variable in a current file refers to the module which will be exported when this this file is required somewhere else. Objects can be made accessible to outside files by using module.exports.

"use strict"; 
var add = function(a, b)
{
	return a + b;
}
var multiply = function(a, b)
{
	return a * b;
}
module.exports = add;

See the above code. When we declare module.exports to be equal to add, we are saying that whenever a file requires this module, export add function.

"use strict"; // Enable Strict Mode
const mymodule = require('./module-ex');
console.log(mymodule(2,5));

In the above code, we require the module-ex module which we just created. When we call the function myModule, it actually calls the add function from the module-ex.js file. See the output.

export add function

Whenever you want a function to be exported by a module, you need to use module.exports.

exports

exports is a short-hand to the module.exports object. One difference is that if you write exports = add instead in module-ex.js, then it won’t work. exports always returns a json object (to simply say). For directly exporting a function, you need to use module.exports. exports can be used to export multiple objects (or functions) along with module.exports.

"use strict"; 
var add = function(a, b)
{
	return a + b;
}
var multiply = function(a, b)
{
	return a * b;
}
exports.add = add;
exports.multiply = multiply;
 
"use strict"; // Enable Strict Mode
const mymodule = require('./module-ex');
console.log("Addition is :" + mymodule.add(2,5));
console.log("Multiplication is :" + mymodule.multiply(2,5));


export multiple objects 3

__dirname

This variable stores the absolute path of the directory which contains the file which is executing the current function. If a function is declared in a.js and used in b.js then __dirname contains the absolute path of directory of a.js i.e. file in which the executing function is declared. NOT the file from which the function is called. See the example at the start of this article for explanation.

__filename

This variable is similar to __dirname but instead of directory, it stores the absolute path of the file which is executing the current function. This is useful if you need to get the current filename or path.

console

As mentioned in the first article, console is a global object consisting of functions like log, error, debug, warn which allow us to write something to the process console appended by a newline character. If you pass a JSON object as an argument, then it prints a formatted JSON object.

global

global is the global object which contains other global variables and functions. You can use global object to define new global variables as per your requirements.

"use strict";
global.myMessage = "This is a global message";
const mymodule = require('./module-ex');
console.log("myMessage");
"use strict"; 
var add = function(a, b)
{
	return a + b;
}
var multiply = function(a, b)
{
	return a * b;
}
console.log("From module-ex.js :" + myMessage);
exports.add = add;

export multiple global variable 3

In this example shown in screenshots, we have declared a new global variable myMessage. Until the instance of node index.js is running, the myMessage will be a global variable accessible to all the modules used in index.js and modules required in other modules.

require

As we you may have guessed by now, require is a global variable. require is used to import other modules into another modules. The usage of require is as follows:
  • require(“myModule”)
    • This command searches for the myModule module in the node_modules/ directory.
  • require(“myModule/file1”)
    • This is used to import only a specific file from a module located in the node_modules/ directory
    • Note that file extension should not be written inside the require function. Node assumes the extensions “.js”, “.json”, “.node”. If file1 is not of any of these extensions, then it throws an error.
  • require(“./myModule”)
    • This looks for a module named myModule in the same directory from where the file requiring this module is located. Again the extensions allowed for myModule are “.js”, “.json” or “.node”.
  • require(“./myFolder”)
    • If your module is spread across an entire folder named myFolder, then requiring this would by default translate to require(“./myFolder/index”)

process

Process is a collection of global variables which define and interact with the current instance of the application. There are too many objects of process variables to be covered here. Some of the objects which you will use frequently are:
  1. process.argv
    • This is an array which contains the arguments which are passed through the command line while calling node.
    • For node index.js name jibin command, the process.argv contains:
    • [ '/usr/bin/nodejs', '/home/jibin/Documents/NodeJS/a4acdemics/index.js', 'name', 'jibin' ]
  2. process.cwd()
    • This is a function which returns the location from where the node script is invoked. It does not hold the location of current function or file BUT the location from where the node instance is started.
  3. process.env
    • It is a JSON object containing all the environment variables declared in your system.
  4. process.stdout , process.stdin, process.stderr
    • These objects contains reference to standard output, standard input and standard error.
  5. process events
    • These are a set of events which are tracked by the node process. More on this in Events and Event Emitter article.
  6. process.exit(errorCode)
    • Used to terminate the current node process.

Popular Videos

communication

How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

Node.js Introduction & Environment Setup
Node Package Manager (NPM)
Node.js Callbacks
Event Loop & Event Emitters in Node.js
Node.js Buffers and Streams
Node.js File System & Setting up File Structure