Global Objects in NodeJS

Last updated on Jan 18 2023
Prabhas Ramanathan

Table of Contents

Node.js – Global Objects

Node.js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below.

__filename

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

Example

Create a js file named main.js with the following code −

 

// Let's try to print the value of __filename

console.log( __filename );
Now run the main.js to see the result −
$ node main.js

Based on the location of your program, it will print the main file name as follows −

/web/com/1427091028_21099/main.js

__dirname

The __dirname represents the name of the directory that the currently executing script resides in.

Example

Create a js file named main.js with the following code −

// Let's try to print the value of __dirname

console.log( __dirname );

Now run the main.js to see the result −
$ node main.js
Based on the location of your program, it will print current directory name as follows −
/web/com/1427091028_21099

setTimeout(cb, ms)

The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.
This function returns an opaque value that represents the timer which can be used to clear the timer.

Example

Create a js file named main.js with the following code −

function printHello() {
console.log( "Hello, World!");
}

// Now call above function after 2 seconds
setTimeout(printHello, 2000);

Now run the main.js to see the result −
$ node main.js
Verify the output is printed after a little delay.
Hello, World!

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.

Example

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);

Now run the main.js to see the result −
$ node main.js
Verify the output where you will not find anything printed.

setInterval(cb, ms)

The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.
This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t).
Example
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 second. Due to system limitation.

Global Objects

The following table provides a list of other objects which we use frequently in our applications. For a more detail, you can refer to the official documentation.

Sr.No. Module Name & Description
1 Console

Used to print information on stdout and stderr.

2 Process

Used to get information on current process. Provides multiple events related to process activities.

Node.js – Utility Modules

There are several utility modules available in Node.js module library. These modules are very common and are frequently used while developing any Node based application.

Sr.No. Module Name & Description
1 OS Module

Provides basic operating-system related utility functions.

2 Path Module

Provides utilities for handling and transforming file paths.

3 Net Module

Provides both servers and clients as streams. Acts as a network wrapper.

4 DNS Module

Provides functions to do actual DNS lookup as well as to use underlying operating system name resolution functionalities.

5 Domain Module

Provides ways to handle multiple different I/O operations as a single group.

So, this brings us to the end of blog. This Tecklearn ‘Global Objects in NodeJS’ blog helps you with commonly asked questions if you are looking out for a job in NodeJS Programming. If you wish to learn NodeJS and build a career in NodeJS Programming domain, then check out our interactive, Node.js Training, that comes with 24*7 support to guide you throughout your learning period.

Node.js Training

About the Course

Tecklearn’s Node.js certification training course familiarizes you with the fundamental concepts of Node.js and provides hands-on experience in building applications efficiently using JavaScript. It helps you to learn how to develop scalable web applications using Express Framework and deploy them using Nginx. You will learn how to build applications backed by MongoDB and gain in-depth knowledge of REST APIs, implement testing, build applications using microservices architecture and write a real-time chat application using Socket IO. Accelerate your career as a Node.js developer by enrolling into this Node.js training.

Why Should you take Node.js Training?

• As per Indeed.com data, the average salary of Node.js developer is about $115000 USD per annum.
• IBM, LinkedIn, Microsoft, GoDaddy, Groupon, Netflix, PayPal, SAP have adopted Node.js – ITJungle.com
• There are numerous job opportunities for Node.js developers worldwide. The job market and popularity of Node.js is constantly growing over the past few years.

What you will Learn in this Course?

Introduction to Node.js

• What is Node.js?
• Why Node.js?
• Installing NodeJS
• Node in-built packages (buffer, fs, http, os, path, util, url)
• Node.js Modules
• Import your own Package
• Node Package Manager (NPM)
• Local and Global Packages

File System Module and Express.js

• File System Module
• Operations associated with File System Module
• JSON Data
• Http Server and Client
• Sending and receiving events with Event Emitters
• Express Framework
• Run a Web Server using Express Framework
• Routes
• Deploy application using PM2 and Nginx

Work with shrink-wrap to lock the node module versions

• What is shrink-wrap
• Working with npmvet
• Working with outdated command
• Install NPM Shrinkwrap

Learn asynchronous programming

• Asynchronous basics
• Call-back functions
• Working with Promises
• Advance promises
• Using Request module to make api calls
• Asynchronous Commands

Integration with MongoDB and Email Servers

• Introduction to NoSQL Databases and MongoDB
• Installation of MongoDB on Windows
• Installation of Database GUI Viewer
• Inserting Documents
• Querying, Updating and Deleting Documents
• Connect MongoDB and Node.js Application
• Exploring SendGrid
• Sending emails through Node.js application using SendGrid

REST APIs and GraphQL

• REST API
• REST API in Express
• Postman
• MongoDB Driver API
• Express Router
• Mongoose API
• GraphQL
• GraphQL Playground

Building Node.js Applications using ES6

• ES6 variables
• Functions with ES6
• Import and Export withES6
• Async/Await
• Introduction to Babel
• Rest API with ES6
• Browsing HTTP Requests with Fetch
• Processing Query String
• Creating API using ES6
• Building Dashboard API
• Creating dashboard UI with EJS
• ES6 Aside: Default Function Parameters
• Data Validation and Sanitization

User Authentication and Application Security

• Authentication
• Types of Authentication
• Session Vs Tokens
• JSON Web Tokens
• Bcrypt
• Node-local storage

Understand Buffers, Streams, and Events

• Using buffers for binary data
• Flowing vs. non-flowing streams
• Streaming I/O from files and other sources
• Processing streams asynchronously
• File System and Security

Build chat application using Socket.io

• Getting Started
• Adding Socket.io To Your App
• Exploring the Front-end
• Sending Live Data Back & Forth
• Creating the Front-end UI
• Showing Messages In App
• Working with Time
• Timestamps
• Show Message Time In Chat App
• Chat application Project

Microservices Application

• Why Microservices?
• What is Microservices?
• Why Docker?
• What is Docker?
• Terminologies in Docker
• Child Processes
• Types of child process

 

0 responses on "Global Objects in NodeJS"

Leave a Message

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