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.