Nodejs Utility Module
Job-ready Online Courses: Knowledge Awaits – Click to Access!
In this article we will be discussing the Nodejs utility module in detail with code and examples.
Nodejs Utility Modules
1. OS Module in Nodejs
It is a built-in utility module in nodejs. To include it in our file we use the require() function. This module is used to get information about the operating system where the code is being executed.
Methods of OS Module:
- os.tmpdir():it will return the operating system’s default directory for temp files.
- os.hostname():it will return the hostname of the operating system.
- os.type():it will return the operating system name.
- os.platform():it will return the operating system platform.
- os.release():it will return the operating system release.
- os.uptime():it will return the system uptime in seconds.
Properties of OS Module:
- os.EOL:It is a constant defining the End-of-line marker for the os.
Code for os module:
const os = require("os"); console.log('Operating System type : ' + os.type()); console.log('Operating System platform : ' + os.platform()); console.log('Operating System total memory : ' + os.totalmem() + " bytes.");
Output
2. Path module in Nodejs
This module is used to get the file paths. To include it in our file we use the require() function.
Methods of Path Module:
- path.join([path1][, path2][, …]):It will Join all the arguments together and normalize the resulting path.
- path.resolve([from …], to):It will resolve to an absolute path.
- path.dirname(p):It will return the directory name of a path.
- path.parse(pathString):It will return an object from a path string.
- path.isAbsolute(path):it will determine whether the path is an absolute path.
Properties of Path Modules:
- path.sep:The platform-specific file separator. ‘\\’ or ‘/’.
- path.delimiter:The platform-specific path delimiter, ; or ‘:’.
Code for path modules:
const path = require('path'); console.log('resolve:' + path.resolve('paths.js')); console.log('File extension:' + path.extname('paths.js'));
Output:
3. DNS module in Nodejs
This module gives us information regarding the network types.To include it in our file we use the require() function.
Methods of DNS Module:
- dns.lookup(hostname[, options], callback): It will resolve a hostname into IPv4 or IPv6 record
- dns.lookupService(address, port, callback): It will resolve the given address and port into a hostname and service using getnameinfo.
- dns.resolve(hostname[, rrtype], callback): It will resolve a hostname into an array of the record types specified by rrtype.
- dns.reverse(ip, callback): It will reverse resolve the ip address to an array of hostnames.
- dns.getServers(): It will resolve an array of IP addresses as strings that are currently being used for resolution.
Code for Dns module:
const dns = require('dns'); dns.lookup("www.data-flair.training", (err, address, family) => { console.log('Address of %s is %j family: IPv%s', 'www.data-flair.training/', address, family); });
Output:
Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!
4. Net module in Nodejs
It is used for the creation of servers and clients. To include it in our file we use the require() function.
Methods of net Module:
- net.createServer([options][, connectionListener]): it will create a new TCP server.
- net.connect(options[, connectionListener]): it will return a new ‘net.Socket’ and connect to the supplied address and port.
- net.createConnection(options[, connectionListener]): it will return a new
- ‘net.Socket’ and connect to the supplied address and port.
- net.connect(port[, host][, connectListener]): it will create a TCP connection to the port on host.
- net.createConnection(port[, host][, connectListener]): it will create a TCP connection to port on host.
- net.isIP(input):Tests if the input is an IP address..
Code for net module:
const net = require('net'); const server = net.createServer(function (connection) { console.log('client connection completed'); connection.on('end', function () { console.log('client has been disconnected'); }); connection.write('Welcome to DataFlair\n'); connection.pipe(connection); }); server.listen(3000, function () { console.log('server listening'); }); const client = net.connect(3000, function () { console.log('Client Connected'); client.write('DataFlair\r\n'); }); client.on('data', function (data) { console.log(data.toString()); client.end(); }); client.on('end', function () { console.log('Server Disconnected'); });
Output:
5. Domain Module in Nodejs
It is used to intercept the errors which are not handled. It can be handled using internal binding or external binding.
Methods of Domain Module:
- domain.add(emitter): it will explicitly add an emitter to the domain.
- domain.remove(emitter):It will remove domain handling from the specified emitter.
- domain.bind(callback): When the returned function is called, any errors that are thrown will be routed to the domain’s error event.
- domain.exit(): It exits the current domain
- domain.dispose(): the domain will no longer be used by callbacks
Properties of Domain Module:
- Domain.members: It is an array of timers and event emitters that have been added to the domain.
Code for domain Module:
let EventEmitter = require("events").EventEmitter; let domain = require("domain"); let emitter1 = new EventEmitter(); let domain1 = domain.create(); domain1.on('error', function (err) { console.log("domain1 handled this error (" + err.message + ")"); }); domain1.add(emitter1); emitter1.on('error', function (err) { console.log("event listener handled this error (" + err.message + ")"); }); emitter1.emit('error', new Error('It will be handled by listener')); emitter1.removeAllListeners('error'); emitter1.emit('error', new Error('It will be handled by domain1')); var domain2 = domain.create(); domain2.on('error', function (err) { console.log("domain2 handled this error (" + err.message + ")"); }); domain2.run(function () { let emitter2 = new EventEmitter(); emitter2.emit('error', new Error('It will be handled by domain2')); }); domain1.remove(emitter1); emitter1.emit('error', new Error('Converted to exception. Program will crash!'));
Output:
domain1 handled this error (It will be handled by domain1)
domain2 handled this error (It will be handled by domain2)
node:events:371
throw er; // Unhandled ‘error’ event
^Error: Converted to exception. Program will crash!
!
Util properties and Methods:
- debuglog():it will write debug messages
- deprecate():it will mark the specified function as deprecated
- format():it will format the string, using the specified arguments
- inherits():it will inherit methods from one function to another
- inspect():it will inspect the object and return it as string
Summary:
In this article, we have thoroughly discussed the various utility modules in node js. For other related topics check the DataFlair website.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google