Programs

What are Global Objects in Node JS?

Introduction

Global object in Node.js offers crucial functionality and is the basis for constructing Node.js applications. These objects offer various features and conveniences, providing developers access to file systems, event handling, module administration, network activity execution, and more. Designing productive and resilient Node.js apps requires awareness of and good usage of these global objects. Follow this blog for more insights.

upGrad offers a Full Stack Software Development Bootcamp programme designed by industry experts to teach job-ready software skills. Learn to build a web application’s backend using Node.js global variable and ExpressJS, perform CRUD operations with MongoDB and develop a dynamic, real-time frontend with React.

What Is Node.js?

Node.js is a JavaScript runtime that enables developers to write client-side and server-side programmes in JavaScript without learning another language. It is neither a programming language nor a software development framework. Thanks to this cross-platform and open-source JavaScript runtime environment, developers can run JavaScript code outside a web browser. It uses the V8 JavaScript engine that powers Google Chrome and other browsers. 

Because of its practical and scalable design, Node.js is well-suited for developing fast and scalable server-side and networking applications. It uses an event-driven, non-blocking I/O (input/output) paradigm to handle multiple requests simultaneously without compromising future processing.

Here’s a code snippet that provides a basic example of how to define a Node.js server using the Express framework:

const express = require('express');

const app = express();

const port = 3000;

app.get('/', (req, res) => {

  res.send('Hello, World!');

});

app.listen(port, () => {

  console.log(`Server listening at http://localhost:${port}`);

});

Depending on the needs, one can create different codes to handle more routes, interact with databases, and carry out various other tasks in Node.js.

Check Out upGrad’s Software Development Courses to upskill yourself.

What Are Global Objects in Node.js?

The global object in Node.js is called ‘global‘. It provides access to several built-in objects, including ‘process’, ‘console’, ‘buffer’, ‘setImmediate()’, ‘clearImmediate()’, and ‘setTimeout()‘, etc. For instance, the process object, an instance of EventEmitter, can be accessed from anywhere in the application, providing details about the running Node.js process. The console object prints to the standard output and standard error streams, while the buffer object handles data in binary format.

In contrast to Node.js, global variables specified in a web browser using the var keyword are not formed as members of the global object.

Why Are Global Objects Used in Node.js?

Global objects in Node.js ease the retrieval of system-level data, the transfer of functionality between modules, and data access across modules. Some of the common uses are:

  • Provides a technique for transferring objects between modules while keeping data and functionality intact.
  • It can be used to declare constants or configuration parameters the application employs.
  • Used to identify critical features that the application will always utilise.
  • It can be used to acquire system-level information such as operating status or environmental conditions.
  • Used to design event emitters that broadcast and receive events across modules.
  • Used to create timers to plan future code execution.

Explore our Popular Software Engineering Courses

Commonly Used Global Objects in Node.js

Global objects in Node.js are pre-built objects that can be used in any module without including them in the application. These items are modules, functions, strings, and actual objects. While some items are accessible from anywhere, others are at the module’s level.

Here are some commonly used global objects in Node.js:

The “console” object

In Node.js, the console object writes data to the standard error (stderr) and standard output (stdout) streams. Console.log(), console.error(), console.warn(), and console.info() are among the methods in this library that display different forms of information. The console object is implemented at a lower level using the process.stdout.write() method.

Here’s an example of using the console object in Node.js:

console.log('Hello, world!');

console.error('This is an error message.');

console.warn('This is a warning message.');

console.info('This is an informational message.');

This code uses the console object to print different types of messages to the console. The output of this code would be:

Hello, world!

This is an error message.

This is a warning message.

This is an informational message.

The “process” object

The process object in Node.js is a global object easily accessible from anywhere. It is an essential component of the Node.js ecosystem since it provides various data sets relevant to an application’s operation. 

The process object, an instance of the EventEmitter class, includes built-in events like exit that can be used to determine when a Node.js application has finished executing. Furthermore, the process object has various other operational properties. Some of these can be incorporated into a Node.js application as a conduit between a command-line interface and the Node.js program.

Here’s an example of using the process object to get the current working directory:

console.log(`Current directory: ${process.cwd()}`);

This program uses the process.cwd() method to get the current working directory and prints it to the console.

Another example is obtaining the command-line arguments supplied to a Node.js program using the process.argv property:

console.log(`Command-line arguments: ${process.argv}`);

This program uses the process.argv property to get the command-line arguments passed to the Node.js program and prints them to the console.

Other attributes of the process object, including env, pid, title, uptime, and memoryUsage, can be used to obtain details about the running process.

The “buffer” object

The Buffer object in Node.js directly manipulates binary data and can be created in various ways. Binary data is represented as a collection of bytes via the Buffer class. Creating a Buffer class instance can convert text into a binary data stream. An application can access the Buffer class without importing the buffer module.

Here’s an example of how to create a Buffer object in Node.js:

// Create an uninitiated Buffer of 10 octets

const buf1 = Buffer.alloc(10);

// Create a Buffer from a given array

const buf2 = Buffer.from([10, 20, 30, 40, 50]);

// Create a Buffer from a given string and optionally encoding type

const buf3 = Buffer.from('Simply Easy Learning', 'utf-8');

The “setInterval” and “clearInterval” methods

In Node.js, the setInterval() method continually executes a function after a fixed delay. It produces a unique interval ID which the clearInterval can subsequently use to halt the function’s repeated future execution.

Here’s an example of using setInterval() and clearInterval() in Node.js:

function sayHello() {

  console.log('Hello!');

}

// Call sayHello() every 1 second

const intervalId = setInterval(sayHello, 1000);

// Stop calling sayHello() after 5 seconds

setTimeout(() => {

  clearInterval(intervalId);

}, 5000);

In this example, the sayHello() method is executed every 1 second using setInterval(). After 5 seconds, clearInterval() is called with the interval ID given by setInterval() to terminate the continued execution of the method.

The clearInterval() function accepts the interval ID returned by setInterval() as its input. If the argument supplied does not indicate an already existing action, this function performs nothing.

upGrad offers a Master of Science in Computer Science from LJMU (Liverpool John Moores University) that specialises in full stack development, focusing on Node.js. 

Explore Our Software Development Free Courses

Conclusion

The global objects by Node.js provide numerous capabilities and utilities, allowing developers to interface with the file system, handle events, manage modules, execute network activities, and more. Enrolling in a suitable course can help master real-time insights in Node.js. 

Check out the Executive PG Programme in Full Stack Development from IIITB, a 13-month online programme co-developed by upGrad. The programme offers the right blend of statistics, technical, and business knowledge. Check out the website for further details.

Frequently Asked Questions

How to declare a global variable in Node.js?

One can use the global keyword to declare a global variable in a JavaScript runtime environment, Node.js. To create a global variable counter, for instance, one can use the code below: global.counter = 0; However, using global variables is usually discouraged to avoid naming conflicts.

What is the difference between global and default scope in Node.js application?

Default scope in Node.js refers to variables declared inside a function that can only be used within the function that declares them. Global scope in Node.js refers to variables available from any program component. Using default variables is usually recommended instead of global variables since it might lead to name disputes and make the code harder to maintain.

What is a JavaScript global variable?

A global variable in JavaScript is defined outside any function and accessible from any function. Global variables are global object properties, which in the case of web browsers is the window object. A global variable in Node.js can be accessed from anywhere in the application, regardless of the file or function scope.

 

Want to share this article?

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks