Learn How to Work With Global Objects in NodeJS

0
4276
Global Objects

 

In this article, we are going to discuss the global objects which are present in the various modules of node.js. The most interesting thing about global objects is that when we are using these objects in our application, then we need not to include these objects i.e. we can call or use these objects directly. Global objects could be the modules, functions, strings and an object itself. Let us understand about the types of the global objects with the following examples.

Global Strings

  • __filename: – The __filename signifies the filename of the code which is under execution. It is nothing but the resolved absolute path of the code file. When working with a main program then it is not unavoidably the same filename which is used in the command line. The path to the module file is the value inside a module as shown below.

When we execute the above code, then we will observe the absolute file path is printed on the console as shown below.

  • __dirname: – The __dirname signifies the name of the directory that exists in the executing script. When we log the value of this global string, then it will print the absolute directory path where the script file exists on the machine drive as shown below.

When we execute the above code, then we will observe the absolute file path at the directory level is printed on the console as shown below.

Global Functions

  • Function setTimeout (callback, milliseconds): – The ‘setTimeout (callback, milliseconds)’ is the global function which is used to run callback after waiting for the given time in the milliseconds. These are the two parameters which are passed to this function. The other factors on which the time delay depends are the OS timer granularity and the system load. The maximum time to which such a timer could span is 24.8 days. The following is an example of the timer function where it calls back a function and prints a string present inside that function after 3000 ms (i.e. 3 seconds).

When we execute the above code, then we will observe the string is printed on the console after 3 seconds delay as shown below.

  • Function clearTimeout (time): – The ‘clearTimeout (time)’ is a global function which is used to stop a timer which was previously created with the help of the ‘setTimeout ()’ function. Here. the parameter time is the timer which is returned by the ‘setTimeout ()’ function. The following is an example of the clearTimeout function which will clear the timer created by the setTimeout function.

When we execute the above code, then we will observe that nothing is printed on the console even after 3 seconds delay as the timeout timer is cancelled by the clearTimeout function.

  • Function setInterval (callback, milliseconds): – The ‘setInterval (callback, milliseconds)’ is the global function which is used to run the callback repetitively after the time interval given in the milliseconds. The other factors on which the time delay depends are the OS timer granularity and system load. The maximum time to which such a timer could span is 24.8 days. The following is an example of the setInterval function, where it calls back a function and prints a string present inside that function repetitively after every 3000 ms (i.e. 3 seconds). Also, it returns an opaque value that signifies the timer. This timer can be cleared by using the function ‘clearInterval (timer)’.

When we execute the above code, then we will observe that the string is printed on the console after every 3 seconds on the console as shown below.

Global Objects
The following table shows a list of other objects which can be used very often in our applications.

1. Console Methods: –In Node.js, a console is a global object which can be used to print different levels of messages to stdout and stderr. The following are the various built-in methods which can be used for printing informational, warning, and error messages.

S No.

Method

Description

1.

console.log([data][, …])

This method is used to print to stdout with the newline. It can take multiple arguments in a printf ()-like fashion.

2.

console.info([data][, …])

This method is used to print to stdout with newline. It can take multiple arguments in a printf ()-like fashion.

3.

console.error([data][, …])

This method is used to print to stderr with newline. It can take multiple arguments in a printf ()-like fashion.

4.

console.warn ([data][, …])

This method is used to print to stderr with newline. It can take multiple arguments in a printf ()-like fashion.

5.

console.dir(obj[, options])

This method uses util.inspect on obj and prints the resulting string to stdout.

6.

console.time (label)

This method is used to mark a time.

7.

console.timeEnd (label)

This method is used to finish timer and record the output.

8.

console.trace (message[, …])

This method is used to print to stderr ‘Trace :’ which is followed by the formatted message and the stack trace to the current position.

9.

console.assert(value[, message][, …])

This method works similar to the assert.ok (), but in this case the error message is formatted as util.format (message…).

Example of console methods: –

2. Process Methods: – The process object is used to get the information on current process. It provides multiple events and methods related to the process activities. Using these methods, we can get the better control over system interactions. The following are some of the Process methods which are frequently used in the application.

1.

abort()

This method is used to cause the node to emit an abort which results in the node to exit and generate a core file.

2.

chdir(directory)

This method is used to change the current working directory of the process or throws an exception upon failure.

3.

cwd ()

This method is used to return the current working directory of the process.

4.

exit([code])

This method is used to end the process with the specified code. If it is omitted then exit uses the ‘success’ code 0.

5.

kill(pid[, signal])

This method is used to send a signal to a process. pid is the process id and signal is the string describing the signal to send.

6.

memoryUsage()

This method is used to return an object describing the memory usage of the Node process which is measured in terms of bytes.

7.

nextTick(callback)

Upon the completion of the current event loop it turns to call the callback function.

8.

uptime()

This method is used to return the number of seconds for which the Node has been running.

Source code for the various global objects in Nodejs
Conclusion: –
In this article, we discussed the various global objects in Node.js which can be referred to directly without importing modules in Node.js along with the supporting examples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here