{"id":87991,"date":"2023-08-14T19:23:19","date_gmt":"2023-08-14T13:53:19","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=87991"},"modified":"2023-08-14T19:23:19","modified_gmt":"2023-08-14T13:53:19","slug":"global-objects-in-nodejs","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/","title":{"rendered":"Global objects in Node.js"},"content":{"rendered":"<p>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.<\/p>\n<p>We will explore some of the essential global objects in Node.js and demonstrate their usage with code examples.<\/p>\n<h4>__filename:<\/h4>\n<p>In Node.js, the \u2018__filename\u2019 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 \u2018__filename\u2019 global object with a code example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">console.log(__filename);\n<\/pre>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/filename-2.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88299\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/filename-2.webp\" alt=\"filename\" width=\"923\" height=\"214\" \/><\/a><\/p>\n<p>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:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/home\/user\/project\/app.js\n<\/pre>\n<p>The \u2018__filename\u2019 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.<\/p>\n<p><strong>Here&#8217;s a practical example that demonstrates the usage of \u2018__filename\u2019:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const path = require('path');\n \nconsole.log(`The current script is located at: ${__filename}`);\n \nconst directory = path.dirname(__filename);\nconsole.log(`The current script is in the directory: ${directory}`);\n<\/pre>\n<h4>__dirname:<\/h4>\n<p>In Node.js, the \u2018__dirname\u2019 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 \u2019 __dirname\u2019 global object with a code example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">console.log(__dirname);\n<\/pre>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/dirname.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88300\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/dirname.webp\" alt=\"dirname\" width=\"918\" height=\"230\" \/><\/a><\/p>\n<p>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:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/home\/user\/project\/\n<\/pre>\n<p>The \u2018__dirname\u2019 global object is useful when you want to access the directory path or resolve file paths relative to the current module.<\/p>\n<p><strong>Here&#8217;s a practical example that demonstrates the usage of \u2018__dirname\u2019:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const path = require('path');\n \nconsole.log(`The current script is located in the directory: ${__dirname}`);\n \nconst filePath = path.join(__dirname, 'data', 'file.txt');\nconsole.log(`The absolute path to file.txt is: ${filePath}`);\n<\/pre>\n<h3>Global Objects:<\/h3>\n<p>The \u2018global\u2019 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&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Accessing global object properties\nconsole.log(global.process); \/\/ Access the 'process' object\n \n\/\/ Modifying global object properties\nglobal.myVariable = 'Hello, Global!';\nconsole.log(myVariable); \/\/ Hello, Global!\n<\/pre>\n<h3>Console Objects:<\/h3>\n<p>The \u2018console\u2019 object provides methods for writing output to the console, which is useful for debugging and logging messages. Here&#8217;s an example of how to use it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Logging messages to the console\nconsole.log('This is a log message');\nconsole.error('This is an error message');\nconsole.warn('This is a warning message');\n<\/pre>\n<h3>Process Objects:<\/h3>\n<p>The \u2018process\u2019 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&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Accessing process-related information\nconsole.log(process.pid); \/\/ Process ID\nconsole.log(process.cwd()); \/\/ Current working directory\nconsole.log(process.argv); \/\/ Command-line arguments\n<\/pre>\n<h3>Module Objects:<\/h3>\n<p>The \u2018module\u2019 object represents the current module in Node.js. It contains information about the current module, such as its filename, exports, and more. Let&#8217;s see an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Accessing module-related information\nconsole.log(module.filename); \/\/ File name of the current module\nconsole.log(module.exports); \/\/ Exported objects and functions\n<\/pre>\n<h3>Require Function:<\/h3>\n<p>Although not a global object itself, the \u2018require\u2019 function is a fundamental part of Node.js. It allows you to load external modules and their functionality into your application. Here&#8217;s a basic usage example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Loading a module using 'require'\nconst fs = require('fs'); \/\/ Load the 'fs' module for file system operations\nfs.readFile('example.txt', 'utf8', (err, data) =&gt; {\n  if (err) throw err;\n  console.log(data);\n});\n<\/pre>\n<p>It&#8217;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 \u2018setTimeout\u2019, \u2018setInterval\u2019, \u2018clearTimeout\u2019, \u2018clearInterval\u2019, and more.<\/p>\n<h4>1. setTimeout FUNCTION:<\/h4>\n<p>The \u2018setTimeout()\u2019 function allows you to execute a specified function after a specified delay in milliseconds. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Call a function after a delay of 2 seconds\nsetTimeout(() =&gt; {\n  console.log('2 seconds have passed');\n}, 2000);\n<\/pre>\n<p>In the above example, the \u2018setTimeout()\u2019 function calls the provided function after a delay of 2 seconds.<\/p>\n<h4>2. setInterval FUNCTION:<\/h4>\n<p>The&#8217;setInterval()&#8217; function enables you to periodically call a certain function after a given milliseconds-long delay. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/\u00a0Call\u00a0a\u00a0function\u00a0repeatedly\u00a0after\u00a0a\u00a0delay\u00a0of\u00a01\u00a0second\nconst intervalId = setInterval(() =&gt; {\n  console.log('1 second has passed');\n}, 1000);\n<\/pre>\n<h4>3. clearTimeout FUNCTION:<\/h4>\n<p>The \u2018clearTimeout()\u2019 function is used to stop the execution of a function that was scheduled to run after a specified delay using \u2018setTimeout()\u2019. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Call a function after a delay of 2 seconds and then stop it using clearTimeout()\nconst timeoutId = setTimeout(() =&gt; {\n  console.log('2 seconds have passed');\n}, 2000);\n \nclearTimeout(timeoutId); \/\/ Stop the execution of the above function\n<\/pre>\n<p>In the above example, the \u2018setTimeout()\u2019 function calls the provided function after a delay of 2 seconds. The \u2018clearTimeout()\u2019 function is then used to stop the execution of the function.<\/p>\n<h4>4. clearInterval FUNCTION:<\/h4>\n<p>The \u2018clearInterval()\u2019 function is used to stop the execution of a function that was scheduled to run repeatedly using \u2018setInterval()\u2019. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Call a function repeatedly after a delay of 1 second and then stop it using clearInterval()\nconst intervalId = setInterval(() =&gt; {\n  console.log('1 second has passed');\n}, 1000);\n \nclearInterval(intervalId); \/\/ Stop the execution of the above function\n<\/pre>\n<p>In the above example, the \u2018setInterval()\u2019 function calls the provided function repeatedly after a delay of 1 second. The \u2018clearInterval()\u2019 function is then used to stop the execution of the function.<\/p>\n<p>While global objects provide convenience, it&#8217;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.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function printHello() {\n   console.log( \"Hello, World!\");\n}\n\/\/ Now call above function after 2 seconds\nvar timeoutObj = setTimeout(printHello, 2000);\n<\/pre>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/clearInterval-FUNCTION.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88301\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/clearInterval-FUNCTION.webp\" alt=\"clear Interval function\" width=\"921\" height=\"144\" \/><\/a><\/p>\n<h4>5. TextEncoder:<\/h4>\n<p>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<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/TextEncoder.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88302 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/TextEncoder.webp\" alt=\"Text Encoder\" width=\"844\" height=\"382\" \/><\/a><\/p>\n<h4>6. TextDecoder:<\/h4>\n<p>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.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/TextDecoder.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88303 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/TextDecoder.webp\" alt=\"Text Decoder:\" width=\"543\" height=\"379\" \/><\/a><\/p>\n<p>By using \u2018TextEncoder\u2019 and \u2018TextDecoder\u2019, 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.<\/p>\n<h4>7. URLSearchParams:<\/h4>\n<p>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.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const paramsString = 'name=John&amp;age=25&amp;city=New York';\nconst searchParams = new URLSearchParams(paramsString);\n \nconsole.log(searchParams.get('name')); \/\/ John\nconsole.log(searchParams.get('age')); \/\/ 25\nconsole.log(searchParams.get('city')); \/\/ New York\n \nsearchParams.append('country', 'USA');\nsearchParams.set('age', '30');\n \nconsole.log(searchParams.toString()); \/\/ name=John&amp;age=30&amp;city=New+York&amp;country=USA\n<\/pre>\n<h3>Conclusion:<\/h3>\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":87993,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4984],"tags":[5113,5114,5115,5116],"class_list":["post-87991","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js-tutorials","tag-global-objects","tag-global-objects-in-tv-nodejs","tag-tv-nodejs","tag-tv-nodejs-in-global-objects"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Global objects in Node.js - TechVidvan<\/title>\n<meta name=\"description\" content=\"These global objects in node.js, you can streamline your development process and enhance the functionality of your Node.js applications.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Global objects in Node.js - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"These global objects in node.js, you can streamline your development process and enhance the functionality of your Node.js applications.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-08-14T13:53:19+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Global objects in Node.js - TechVidvan","description":"These global objects in node.js, you can streamline your development process and enhance the functionality of your Node.js applications.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/","og_locale":"en_US","og_type":"article","og_title":"Global objects in Node.js - TechVidvan","og_description":"These global objects in node.js, you can streamline your development process and enhance the functionality of your Node.js applications.","og_url":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-08-14T13:53:19+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Global objects in Node.js","datePublished":"2023-08-14T13:53:19+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/"},"wordCount":918,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#primaryimage"},"thumbnailUrl":"","keywords":["Global objects","Global objects in TV Nodejs","TV Nodejs","TV Nodejs in Global objects"],"articleSection":["Node Js Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/","url":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/","name":"Global objects in Node.js - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-08-14T13:53:19+00:00","description":"These global objects in node.js, you can streamline your development process and enhance the functionality of your Node.js applications.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/global-objects-in-nodejs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Global objects in Node.js"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87991","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=87991"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87991\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=87991"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=87991"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=87991"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}