SlideShare a Scribd company logo
1 of 9
Download to read offline
Global objects in Node.js
One of the key features of Node.js is the availability of global objects. These
objects are accessible throughout your application without requiring explicit
declaration, making them convenient for various tasks.
We will explore some of the essential global objects in Node.js and
demonstrate their usage with code examples.
__filename:
In Node.js, the ‘__filename’ global object provides the absolute path of the
current module file. It represents the filename of the script that is currently
being executed. In this section, we will explore the usage of the ‘__filename’
global object with a code example.
console.log(__filename);
When you execute the above code in a Node.js application, it will print the
absolute path of the current module file, including the filename. For example:
/home/user/project/app.js
The ‘__filename’ global object is particularly useful when you want to access
the file path or extract information about the current module being executed.
It allows you to dynamically reference the current file within your code.
Here’s a practical example that demonstrates the usage of ‘__filename’:
const path = require('path');
console.log(`The current script is located at: ${__filename}`);
const directory = path.dirname(__filename);
console.log(`The current script is in the directory:
${directory}`);
__dirname:
In Node.js, the ‘__dirname’ global object represents the directory name of the
current module file. It provides the absolute path of the directory containing
the currently executing script. In this section, we will explore the usage of the ’
__dirname’ global object with a code example.
console.log(__dirname);
When you execute the above code in a Node.js application, it will print the
absolute path of the directory containing the current module file. For example:
/home/user/project/
The ‘__dirname’ global object is useful when you want to access the directory
path or resolve file paths relative to the current module.
Here’s a practical example that demonstrates the usage of ‘__dirname’:
const path = require('path');
console.log(`The current script is located in the directory:
${__dirname}`);
const filePath = path.join(__dirname, 'data', 'file.txt');
console.log(`The absolute path to file.txt is: ${filePath}`);
Global Objects:
The ‘global’ object is the root object of the Node.js runtime environment. It
provides properties and methods that are available globally in your
application. While using global objects is generally discouraged due to
potential naming conflicts, understanding their capabilities is crucial. Here’s
an example:
// Accessing global object properties
console.log(global.process); // Access the 'process' object
// Modifying global object properties
global.myVariable = 'Hello, Global!';
console.log(myVariable); // Hello, Global!
Console Objects:
The ‘console’ object provides methods for writing output to the console, which
is useful for debugging and logging messages. Here’s an example of how to use
it:
// Logging messages to the console
console.log('This is a log message');
console.error('This is an error message');
console.warn('This is a warning message');
Process Objects:
The ‘process’ object provides information and controls over the current
Node.js process. It contains properties and methods that allow you to interact
with the environment, access command-line arguments, and more. Here’s an
example:
// Accessing process-related information
console.log(process.pid); // Process ID
console.log(process.cwd()); // Current working directory
console.log(process.argv); // Command-line arguments
Module Objects:
The ‘module’ object represents the current module in Node.js. It contains
information about the current module, such as its filename, exports, and
more. Let’s see an example:
// Accessing module-related information
console.log(module.filename); // File name of the current module
console.log(module.exports); // Exported objects and functions
Require Function:
Although not a global object itself, the ‘require’ function is a fundamental part
of Node.js. It allows you to load external modules and their functionality into
your application. Here’s a basic usage example:
// Loading a module using 'require'
const fs = require('fs'); // Load the 'fs' module for file
system operations
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
It’s worth noting that the global objects mentioned above are just a subset of
what Node.js offers. There are additional global objects and functions
available that serve specific purposes, such as ‘setTimeout’, ‘setInterval’,
‘clearTimeout’, ‘clearInterval’, and more.
1. setTimeout FUNCTION:
The ‘setTimeout()’ function allows you to execute a specified function after a
specified delay in milliseconds. Here’s an example:
// Call a function after a delay of 2 seconds
setTimeout(() => {
console.log('2 seconds have passed');
}, 2000);
In the above example, the ‘setTimeout()’ function calls the provided function
after a delay of 2 seconds.
2. setInterval FUNCTION:
The’setInterval()’ function enables you to periodically call a certain function
after a given milliseconds-long delay. Here’s an example:
// Call a function repeatedly after a delay of 1 second
const intervalId = setInterval(() => {
console.log('1 second has passed');
}, 1000);
3. clearTimeout FUNCTION:
The ‘clearTimeout()’ function is used to stop the execution of a function that
was scheduled to run after a specified delay using ‘setTimeout()’. Here’s an
example:
// Call a function after a delay of 2 seconds and then stop it
using clearTimeout()
const timeoutId = setTimeout(() => {
console.log('2 seconds have passed');
}, 2000);
clearTimeout(timeoutId); // Stop the execution of the above
function
In the above example, the ‘setTimeout()’ function calls the provided function
after a delay of 2 seconds. The ‘clearTimeout()’ function is then used to stop
the execution of the function.
4. clearInterval FUNCTION:
The ‘clearInterval()’ function is used to stop the execution of a function that
was scheduled to run repeatedly using ‘setInterval()’. Here’s an example:
// Call a function repeatedly after a delay of 1 second and then
stop it using clearInterval()
const intervalId = setInterval(() => {
console.log('1 second has passed');
}, 1000);
clearInterval(intervalId); // Stop the execution of the above
function
In the above example, the ‘setInterval()’ function calls the provided function
repeatedly after a delay of 1 second. The ‘clearInterval()’ function is then used
to stop the execution of the function.
While global objects provide convenience, it’s generally recommended to limit
their usage and opt for modular code. Excessive reliance on global objects can
lead to potential conflicts and make your code harder to maintain and test.
function printHello() {
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
var timeoutObj = setTimeout(printHello, 2000);
5. TextEncoder:
The TextEncoder class is used to encode JavaScript strings into a specified
character encoding. It provides the encode() method to convert a string into
an encoded Uint8Array
6. TextDecoder:
The TextDecoder class is used to decode binary data, such as Uint8Array, into
JavaScript strings using a specified character encoding. It provides the
decode() method to convert the encoded data into a string.
By using ‘TextEncoder’ and ‘TextDecoder’, you can handle text encoding and
decoding in different character encodings, allowing you to work with data in
various formats. These classes are particularly useful when dealing with
network communication, file I/O, or any scenario where you need to convert
text between different encodings.
7. URLSearchParams:
The URLSearchParams is a built-in JavaScript class that provides utility
methods for working with the query parameters of a URL. It allows you to
parse, manipulate, and serialize query strings in a convenient manner. The
URLSearchParams class is particularly useful when dealing with URLs and
handling query parameters dynamically.
const paramsString = 'name=John&age=25&city=New York';
const searchParams = new URLSearchParams(paramsString);
console.log(searchParams.get('name')); // John
console.log(searchParams.get('age')); // 25
console.log(searchParams.get('city')); // New York
searchParams.append('country', 'USA');
searchParams.set('age', '30');
console.log(searchParams.toString()); //
name=John&age=30&city=New+York&country=USA
Conclusion:
Understanding the global objects in Node.js is crucial for building robust
server-side applications. By leveraging the capabilities of these global objects,
you can streamline your development process and enhance the functionality of
your Node.js applications.

More Related Content

Similar to Global objects in Node.pdf

Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_javaardnetij
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slideshelenmga
 
Utility Modules in Node.js.pdf
Utility Modules in Node.js.pdfUtility Modules in Node.js.pdf
Utility Modules in Node.js.pdfSudhanshiBakre1
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84Mahmoud Samir Fayed
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 

Similar to Global objects in Node.pdf (20)

GradleFX
GradleFXGradleFX
GradleFX
 
NodeJs Session02
NodeJs Session02NodeJs Session02
NodeJs Session02
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Ch23
Ch23Ch23
Ch23
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_java
 
treeview
treeviewtreeview
treeview
 
treeview
treeviewtreeview
treeview
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Utility Modules in Node.js.pdf
Utility Modules in Node.js.pdfUtility Modules in Node.js.pdf
Utility Modules in Node.js.pdf
 
Book
BookBook
Book
 
iOS Application Development
iOS Application DevelopmentiOS Application Development
iOS Application Development
 
backend
backendbackend
backend
 
backend
backendbackend
backend
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Test02
Test02Test02
Test02
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 

More from SudhanshiBakre1

Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdfSudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfSudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdfSudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdfSudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfSudhanshiBakre1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdfSudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdfSudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfSudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfSudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfSudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 

Recently uploaded

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Global objects in Node.pdf

  • 1. Global objects in Node.js One of the key features of Node.js is the availability of global objects. These objects are accessible throughout your application without requiring explicit declaration, making them convenient for various tasks. We will explore some of the essential global objects in Node.js and demonstrate their usage with code examples. __filename: In Node.js, the ‘__filename’ global object provides the absolute path of the current module file. It represents the filename of the script that is currently being executed. In this section, we will explore the usage of the ‘__filename’ global object with a code example. console.log(__filename); When you execute the above code in a Node.js application, it will print the absolute path of the current module file, including the filename. For example: /home/user/project/app.js The ‘__filename’ global object is particularly useful when you want to access the file path or extract information about the current module being executed. It allows you to dynamically reference the current file within your code.
  • 2. Here’s a practical example that demonstrates the usage of ‘__filename’: const path = require('path'); console.log(`The current script is located at: ${__filename}`); const directory = path.dirname(__filename); console.log(`The current script is in the directory: ${directory}`); __dirname: In Node.js, the ‘__dirname’ global object represents the directory name of the current module file. It provides the absolute path of the directory containing the currently executing script. In this section, we will explore the usage of the ’ __dirname’ global object with a code example. console.log(__dirname); When you execute the above code in a Node.js application, it will print the absolute path of the directory containing the current module file. For example: /home/user/project/ The ‘__dirname’ global object is useful when you want to access the directory path or resolve file paths relative to the current module. Here’s a practical example that demonstrates the usage of ‘__dirname’: const path = require('path');
  • 3. console.log(`The current script is located in the directory: ${__dirname}`); const filePath = path.join(__dirname, 'data', 'file.txt'); console.log(`The absolute path to file.txt is: ${filePath}`); Global Objects: The ‘global’ object is the root object of the Node.js runtime environment. It provides properties and methods that are available globally in your application. While using global objects is generally discouraged due to potential naming conflicts, understanding their capabilities is crucial. Here’s an example: // Accessing global object properties console.log(global.process); // Access the 'process' object // Modifying global object properties global.myVariable = 'Hello, Global!'; console.log(myVariable); // Hello, Global! Console Objects: The ‘console’ object provides methods for writing output to the console, which is useful for debugging and logging messages. Here’s an example of how to use it: // Logging messages to the console
  • 4. console.log('This is a log message'); console.error('This is an error message'); console.warn('This is a warning message'); Process Objects: The ‘process’ object provides information and controls over the current Node.js process. It contains properties and methods that allow you to interact with the environment, access command-line arguments, and more. Here’s an example: // Accessing process-related information console.log(process.pid); // Process ID console.log(process.cwd()); // Current working directory console.log(process.argv); // Command-line arguments Module Objects: The ‘module’ object represents the current module in Node.js. It contains information about the current module, such as its filename, exports, and more. Let’s see an example: // Accessing module-related information console.log(module.filename); // File name of the current module console.log(module.exports); // Exported objects and functions Require Function:
  • 5. Although not a global object itself, the ‘require’ function is a fundamental part of Node.js. It allows you to load external modules and their functionality into your application. Here’s a basic usage example: // Loading a module using 'require' const fs = require('fs'); // Load the 'fs' module for file system operations fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); It’s worth noting that the global objects mentioned above are just a subset of what Node.js offers. There are additional global objects and functions available that serve specific purposes, such as ‘setTimeout’, ‘setInterval’, ‘clearTimeout’, ‘clearInterval’, and more. 1. setTimeout FUNCTION: The ‘setTimeout()’ function allows you to execute a specified function after a specified delay in milliseconds. Here’s an example: // Call a function after a delay of 2 seconds setTimeout(() => { console.log('2 seconds have passed'); }, 2000); In the above example, the ‘setTimeout()’ function calls the provided function after a delay of 2 seconds.
  • 6. 2. setInterval FUNCTION: The’setInterval()’ function enables you to periodically call a certain function after a given milliseconds-long delay. Here’s an example: // Call a function repeatedly after a delay of 1 second const intervalId = setInterval(() => { console.log('1 second has passed'); }, 1000); 3. clearTimeout FUNCTION: The ‘clearTimeout()’ function is used to stop the execution of a function that was scheduled to run after a specified delay using ‘setTimeout()’. Here’s an example: // Call a function after a delay of 2 seconds and then stop it using clearTimeout() const timeoutId = setTimeout(() => { console.log('2 seconds have passed'); }, 2000); clearTimeout(timeoutId); // Stop the execution of the above function In the above example, the ‘setTimeout()’ function calls the provided function after a delay of 2 seconds. The ‘clearTimeout()’ function is then used to stop the execution of the function.
  • 7. 4. clearInterval FUNCTION: The ‘clearInterval()’ function is used to stop the execution of a function that was scheduled to run repeatedly using ‘setInterval()’. Here’s an example: // Call a function repeatedly after a delay of 1 second and then stop it using clearInterval() const intervalId = setInterval(() => { console.log('1 second has passed'); }, 1000); clearInterval(intervalId); // Stop the execution of the above function In the above example, the ‘setInterval()’ function calls the provided function repeatedly after a delay of 1 second. The ‘clearInterval()’ function is then used to stop the execution of the function. While global objects provide convenience, it’s generally recommended to limit their usage and opt for modular code. Excessive reliance on global objects can lead to potential conflicts and make your code harder to maintain and test. function printHello() { console.log( "Hello, World!"); } // Now call above function after 2 seconds var timeoutObj = setTimeout(printHello, 2000); 5. TextEncoder:
  • 8. The TextEncoder class is used to encode JavaScript strings into a specified character encoding. It provides the encode() method to convert a string into an encoded Uint8Array 6. TextDecoder: The TextDecoder class is used to decode binary data, such as Uint8Array, into JavaScript strings using a specified character encoding. It provides the decode() method to convert the encoded data into a string. By using ‘TextEncoder’ and ‘TextDecoder’, you can handle text encoding and decoding in different character encodings, allowing you to work with data in various formats. These classes are particularly useful when dealing with network communication, file I/O, or any scenario where you need to convert text between different encodings. 7. URLSearchParams: The URLSearchParams is a built-in JavaScript class that provides utility methods for working with the query parameters of a URL. It allows you to parse, manipulate, and serialize query strings in a convenient manner. The URLSearchParams class is particularly useful when dealing with URLs and handling query parameters dynamically. const paramsString = 'name=John&age=25&city=New York'; const searchParams = new URLSearchParams(paramsString); console.log(searchParams.get('name')); // John console.log(searchParams.get('age')); // 25
  • 9. console.log(searchParams.get('city')); // New York searchParams.append('country', 'USA'); searchParams.set('age', '30'); console.log(searchParams.toString()); // name=John&age=30&city=New+York&country=USA Conclusion: Understanding the global objects in Node.js is crucial for building robust server-side applications. By leveraging the capabilities of these global objects, you can streamline your development process and enhance the functionality of your Node.js applications.