{"id":87994,"date":"2023-08-11T07:00:41","date_gmt":"2023-08-11T01:30:41","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=87994"},"modified":"2023-08-11T07:00:41","modified_gmt":"2023-08-11T01:30:41","slug":"nodejs-utility-modules","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/","title":{"rendered":"Utility Modules in Node.js"},"content":{"rendered":"<p>One of the strengths of Node.js lies in its utility modules, which provide essential tools and functionalities to streamline development processes. In this article, we will delve into some key utility modules in Node.js and showcase their practical usage with code examples.<\/p>\n<h3>Module Name and Description:<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Module-Name-and-Description-1.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88289 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Module-Name-and-Description-1.webp\" alt=\"Module Name and Description\" width=\"894\" height=\"592\" \/><\/a><\/p>\n<h3>Util Module<\/h3>\n<p>The util module is a core module in Node.js that offers a variety of utility functions for debugging, formatting, and working with objects. Let&#8217;s see a few common use cases:<\/p>\n<p><strong>a) Inheriting Objects:<\/strong> The \u2018util.inherits\u2019 function allows you to create object inheritance in Node.js. It sets up the prototype chain between two constructors, enabling prototype-based inheritance.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const util = require('util');\n \nfunction Parent() {}\nParent.prototype.greet = function() {\n    console.log('Hello, I am the parent.');\n}\n \nfunction Child() {}\nutil.inherits(Child, Parent);\n \nconst childObj = new Child();\nchildObj.greet(); \/\/ Output: Hello, I am the parent.\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hello, I am the parent.<\/p>\n<p><strong>b) Promisify:<\/strong> The \u2018util.promisify\u2019 function is used to convert callback-based functions into Promise-based functions, simplifying asynchronous operations. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const util = require('util');\nconst fs = require('fs');\n \nconst readFileAsync = util.promisify(fs.readFile);\n \nreadFileAsync('file.txt', 'utf8')\n    .then(data =&gt; console.log(data))\n    .catch(err =&gt; console.error(err));\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Hello, World!<\/p>\n<p>Hence the file.txt contains Hello, World!<\/p>\n<h4>Path Module<\/h4>\n<p>The path module offers tools for navigating between files and directories. It helps in handling cross-platform path compatibility and resolving file paths correctly. Consider the following examples:<\/p>\n<p><strong>a) Resolving Paths:<\/strong> The &#8216;path.resolve&#8217; method resolves a series of routes or path segments into an absolute path.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Require path\nconst path = require('path');\n \n\/\/ Display Resolve\nconsole.log('resolve:' + path.resolve('paths.js'));\n \n\/\/ Display Extension\nconsole.log('extension:' + path.extname('paths.js'));\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Utility-Modules-output-.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88286 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Utility-Modules-output-.webp\" alt=\"Utility Modules output\" width=\"923\" height=\"188\" \/><\/a><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const path = require('path');\n \nconst filePath = '\/path\/to\/file.txt';\nconst fileInfo = path.parse(filePath);\n \nconsole.log(fileInfo);\n\/* Output:\n{\n    root: '\/',\n    dir: '\/path\/to',\n    base: 'file.txt',\n    ext: '.txt',\n    name: 'file'\n}\n*\/\n<\/pre>\n<h4>Crypto Module<\/h4>\n<p>The crypto module provides cryptographic functionalities, such as generating secure hashes, encrypting and decrypting data, and creating digital signatures. Let&#8217;s see an example of generating an MD5 hash:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const crypto = require('crypto');\n \nconst data = 'Hello, World!';\nconst hash = crypto.createHash('md5').update(data).digest('hex');\n \nconsole.log(hash); \/\/ Output: 6cd3556deb0da54bca060b4c39479839\n<\/pre>\n<h4>OS Module<\/h4>\n<p>The OS module provides a set of utility methods for interacting with the operating system. It allows developers to retrieve information about the operating system, and network interfaces, and perform certain system-related operations. Here are a few notable use cases:<\/p>\n<p><strong>a) Retrieving Operating System Information:<\/strong><\/p>\n<p>The OS module provides functions to retrieve information about the operating system, such as the platform, hostname, and architecture.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Require operating System module\nconst os = require(\"os\");\n \n\/\/ Display operating System type\nconsole.log('Operating System type : ' + os.type());\n \n\/\/ Display operating System platform\nconsole.log('platform : ' + os.platform());\n \n\/\/ Display total memory\nconsole.log('total memory : ' + os.totalmem() + \" bytes.\");\n \n\/\/ Display available memory\nconsole.log('Available memory : ' + os.availmem() + \" bytes.\");\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/utility-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88386 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/utility-output.webp\" alt=\"utility output\" width=\"924\" height=\"187\" \/><\/a><\/p>\n<h4>Net Module<\/h4>\n<p>For building both servers and clients, the net module offers a set of asynchronous network APIs. It allows you to create TCP or IPC (inter-process communication) servers and establish network connections with other servers. Here&#8217;s an example of creating a TCP server:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Require net module\nconst net = require('net');\n \nconst server = net.createServer(function (connection) {\n    console.log('client connected'); connection.on('end', function () {\n        console.log('client disconnected');\n    });\n    connection.write('Hello World!\\r\\n'); connection.pipe(connection);\n});\n \nserver.listen(8080, function () {\n    console.log('server listening');\n});\n<\/pre>\n<h4>Client-side:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const net = require('net');\n \nconst client = net.connect(8124, function () {\n    console.log('Client Connected');\n    client.write('Hello World\\r\\n');\n});\n \nclient.on('data', function (data) {\n    console.log(data.toString());\n    client.end();\n});\n \nclient.on('end', function () {\n    console.log('Server Disconnected');\n});\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Server listening<\/p>\n<p>Client Connected<br \/>\nHello World<br \/>\nServer Disconnected<\/p>\n<h4>DNS Module<\/h4>\n<p>The DNS module provides functions to perform DNS (Domain Name System) lookups and resolve domain names. It allows you to convert domain names to IP addresses and vice versa. Here&#8217;s an example of resolving a domain name:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Require dns module\nconst dns = require('dns');\n \n\/\/ Store the web address\nconst website = 'www.google.com ';\n \n\/\/ Call lookup function of DNS\ndns.lookup(website, (err, address, family) =&gt; {\n    console.log('Address of %s is %j family: IPv%s',\n        website, address, family);\n});\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Address of www.google.com is &#8220;203.92.39.72&#8221;<br \/>\nfamily: IPv4<\/p>\n<h4>Domain Module<\/h4>\n<p>The domain module provides a way to handle uncaught exceptions in a graceful manner, isolating them within a specific domain. It helps in managing errors and preventing the termination of the entire application due to an unhandled exception. However, note that the domain module has been deprecated since Node.js v10.0.0. It is recommended to use try&#8230;catch and other error-handling mechanisms provided by Node.js.<\/p>\n<p><strong>An example of how the domain module could have been used in earlier versions of Node.js:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">const EventEmitter = require(\"events\").EventEmitter;\nconst domain = require(\"domain\");\nconst emit_a = new EventEmitter();\nconst dom_a = domain.create();\n \ndom_a.on('error', function (err) {\n    console.log(\"Error handled by dom_a (\" + err.message + \")\");\n});\n \ndom_a.add(emit_a);\nemit_a.on('error', function (err) {\n    console.log(\"listener handled this error (\" + err.message + \")\");\n});\n \nemit_a.emit('error', new Error('Listener handles this'));\nemit_a.removeAllListeners('error');\nemit_a.emit('error', new Error('Dom_a handles this'));\nconst dom_b = domain.create();\n \ndom_b.on('error', function (err) {\n    console.log(\"Error handled by dom_b (\" + err.message + \")\");\n});\n \ndom_b.run(function () {\n    const emit_b = new EventEmitter();\n    emit_b.emit('error', new Error('Dom_b handles this'));\n});\n \ndom_a.remove(emit_a);\nemit_a.emit('error', new Error('Exception message...!'));\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Domain-Module-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88291 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/08\/Domain-Module-output.webp\" alt=\"Domain Module output\" width=\"850\" height=\"381\" \/><\/a><\/p>\n<h3>Conclusion<\/h3>\n<p>Node.js utility modules play a vital role in enhancing productivity and simplifying common tasks during development. The utility module offers various useful functions for debugging and working with objects, while the path module provides utilities for handling file paths. Additionally, the crypto module empowers developers with cryptographic capabilities.<\/p>\n<p>The OS, NET, DNS, and domain modules in Node.js offer essential functionalities for working with the operating system, networking, DNS lookups, and error handling. These modules enable developers to create robust and efficient applications while interacting with various system components and services.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One of the strengths of Node.js lies in its utility modules, which provide essential tools and functionalities to streamline development processes. In this article, we will delve into some key utility modules in Node.js&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":87996,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4984],"tags":[5110,5117,5118,5119],"class_list":["post-87994","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js-tutorials","tag-nodejs","tag-nodejs-in-utility-modules","tag-utility-modules","tag-utility-modules-in-nodejs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Utility Modules in Node.js - TechVidvan<\/title>\n<meta name=\"description\" content=\"The utility module in nodejs offers various useful functions for debugging and working with objects, while the path module provides utilities.\" \/>\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\/nodejs-utility-modules\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Utility Modules in Node.js - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"The utility module in nodejs offers various useful functions for debugging and working with objects, while the path module provides utilities.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/\" \/>\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-11T01:30:41+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=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Utility Modules in Node.js - TechVidvan","description":"The utility module in nodejs offers various useful functions for debugging and working with objects, while the path module provides utilities.","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\/nodejs-utility-modules\/","og_locale":"en_US","og_type":"article","og_title":"Utility Modules in Node.js - TechVidvan","og_description":"The utility module in nodejs offers various useful functions for debugging and working with objects, while the path module provides utilities.","og_url":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-08-11T01:30:41+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":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Utility Modules in Node.js","datePublished":"2023-08-11T01:30:41+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/"},"wordCount":583,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#primaryimage"},"thumbnailUrl":"","keywords":["Nodejs","Nodejs in Utility Modules","Utility Modules","Utility modules in nodejs"],"articleSection":["Node Js Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/","url":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/","name":"Utility Modules in Node.js - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-08-11T01:30:41+00:00","description":"The utility module in nodejs offers various useful functions for debugging and working with objects, while the path module provides utilities.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/nodejs-utility-modules\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Utility Modules 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\/87994","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=87994"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87994\/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=87994"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=87994"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=87994"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}