Utility Module in Node.js
The Node.js Library Module provides many Utility Modules that help you a lot while developing applications on Node.js. The following table lists and describes these Utility Modules.
The Node.js Library Module provides many Utility Modules that help you a lot while developing applications on Node.js. The following table lists and describes these Utility Modules.
No. Module Name & Description1 os ModuleProvides basic utility functions related to the operating system. 2 path Module
Provides utilities to handle and transform the path to the file. 3 net Module
Works as Network Wrapper, turns Server and Client into Streams. 4 dns Module
Provides functions to perform DNS Lookup. 5 domain Module
Used to interfere with unresolved errors
1. OS Module in Node.js
The OS Module in Node.js provides basic operating system-related functions. This module can be imported by the following syntax:
var os = require ( "os" )
Method of the os Module in Node.js
Stt Method & Description1 os.tmpdir ()Returns the default directory for temporary files 3 os.hostname ()
Returns the operating system hostname. 4 os.type ()
Returns the name of the OS. 5 os.platform ()
Returns the operating system platform. 6 os.arch ()
Returns the CPU structure of the OS. 7 os.totalmem ()
Returns the total amount of memory (byte units). 8 os.freemem ()
Returns the total amount of unused memory (byte units). 9 os.cpus ()
Returns the array of objects containing information about CPU / core: model, speed (MHz value), and time. 10 os.networkInterfaces ()
Get the list of Network Interface.
Properties of the os Module in Node.js
os.EOL : A End-Of-Line definition of the operating system.
For example
Below is an example to illustrate some methods of the os Module in Node.js. You create main.js with the following content:
var os = require ( "os" ); // Print information about OS console . log ( 'OS Type la:' + os . type ()); // Print information on OS platform console . log ( 'OS Platform:' + os . platform ()); // Print information about the console . log ( ' Application :' + os . totalmem () + "byte." ); // Print information about the console console . log ( 'The file is whip:' + os . freemem () + "byte." );
Run main.js to see the result ::
$ node main . js
Check the result:
OS Type la: Linux
OS Platform: linux
Tongue size: 25103400960 bytes.
Blade size: 20676710400 bytes.
2. Path Module in Node.js
The path Module in is used to Resolve and convert the path to the file. This module can be inport according to the syntax:
var path = require ( "path" )
Method of path Module in Node.js
Method & Description1 path.normalize (p)Standardize path 2 path.join ([path1] [, path2] [, .])
Combine all the path parameters together and then normalize the resulting path to create 3 path.resolve ([from .], big)
Resolve an absolute path. 4 path.isAbsolute (path)
Determine if it is an absolute path. An absolute path always points to the same location, regardless of the working directory. 5 path.relative (from, to)
Resolve a relative path. 6 path.dirname (p)
Returns the directory name of a path. 7 path.basename (p [, ext])
Returns the last part of an 8 path.extname (p)
Returns the tail of the path (eg txt) 9 path.parse (pathString)
Returns an object from a string representing the 10 path.format path (pathObject)
Returns a string representing the path from an object, which is in contrast to the above path.parse method.
Properties of path Module in Node.js
Stability Properties & Description1 path.sepFile Separator manifest of specific platform. It could be '' or '/'. Path.delimiter 2
Path Delimiter expression of specific platform, may be ';' or ':'.
For example
The following example illustrates how to use some methods and properties of the Path Module in Node.js. You create main.js with the following content:
var path = require ( "path" ); // Check out the normalize () console . log ( ' Method th NORMALIZE:' + path . normalize ( '/ test / test1 // 2slashes / 1slash / tab / .' )); // Ket hop the following information to create a console . log ( 'Method of JOIN:' + path . join ( '/ test' , 'test1' , '2slashes / 1slash' , 'tab' , '.' )); // Resolve a console game . log ( 'Phuong thuc RESOLVE:' + path . resolve ( 'main.js' )); // Lay out the information on the console . log ( 'Phuong thuc EXTNAME:' + path . extname ( 'main.js' ));
Run main.js to see the result ::
$ node main . js
Check the result.
Method of NORMALIZE: / test / test1 / 2slashes / 1slash
Phuong thuc JOIN: / test / test1 / 2slashes / 1slash
Phuong thuc RESOLVE: /web/com/1427176256_27423/main.js
Phuong thuc EXTNAME: .js
3. Net Module in Node.js
Net Module in Node.js is used to create Server and Client. This module provides an asynchronous Network Wrapper and can be imported with the syntax:
var net = require ( "net" )
Method of net Module in Node.js
Method & Description1 net.createServer ([options] [, connectionListener])Create a new TCP Server. The connectionListener parameter is automatically set to become a Listener for the 'connection' event. 2 net.connect (options [, connectionListener])
This is a factory method, returning a new 'net.Socket' and connecting to the given address and port. 3 net.createConnection (options [, connectionListener])
This is a factory method, returning a new 'net.Socket' and connecting to the given address and port. 4 net.connect (port [, host] [, connectListener])
Create a TCP connection to the port on the given host. If the host is not provided, the default value is 'localhost'. The connectListener parameter will be added as the Listener for the 'connect' event. 5 net.createConnection (port [, host] [, connectListener])
Create a TCP connection to the port on the given host. If the host is not provided, the default value is 'localhost'. The connectListener parameter will be added as the Listener for the 'connect' event. 6 net.connect (path [, connectListener])
Create a Unix Socket connection to the given path. The connectListener parameter will be added as the Listener for the 'connect' event. 7 net.createConnection (path [, connectListener])
Create a Unix Socket connection to the given path. The connectListener parameter will be added as the Listener for the 'connect' event. 8 net.isIP (input)
Check if the input is an IP address. Returns 0 for an invalid string, 4 for the IP address version v4, and returns 6 for the v6 IP address. 9 net.isIPv4 (input)
Returns true if input is IP address v4, otherwise false. 10 net.isIPv6 (input)
Returns true if input is a v6 IP address, otherwise false.
The net.Server class in Node.js
The net.Server class is used to create a TCP Server or Local Server.
Method of net.Server class in Node.js
Method & Description1 server.listen (port [, host] [, backlog] [, callback])Start accepting the connection on the port and the given host. If no host parameter is provided, the Server accepts direct connections to any IPv4 address (INADDR_ANY). If the port value of 0 will assign a random port. 2 server.listen (path [, callback])
Start a Local Server to listen for connections on the given path. 3 server.listen (handle [, callback])
Object handle can be set for Server or Socket. This causes the Server to accept a connection to a specific handle. 4 server.listen (options [, callback])
The options parameter can be port, host, and backlog attributes. The callback parameter is an arbitrary callback function that works like when calling the server.listen method (port, [host], [backlog], [callback]). 5 server.close ([callback])
Closing all connections has ended and the Server generates a 'close' event. 6 server.address ()
Returns a bound address address and port of the Server, as reported by the OS. 7 server.unref ()
Calling the unref method on a Server will allow the program to exit. 8 server.ref ()
In contrast to the unref () method, calling the ref () method will not allow the program to exit. 9 server.getConnections (callback)
Asynchronously get the number of concurrent connections on a Server. The callback function should take two parameters err (to resolve errors) and count (to count).
The event of net.Server class in Node.js
No. Events & Description1 listeningOccurs when the Server is mounted after a call to server.listen. 2 connection
Occurs when creating a new connection 3 close
Occurs when closing Server 4 error
Occurs when any errors occur. The 'close' event will be directly called after this event.
The net.Socket class in Node.js
This object is an abstract class of TCP or Local Socket. net.Socket inherits the duplex Stream interface. They can be created by the user or by a Client (by the connect () method) or can be created by Node.js and transmitted to the user via the 'connection' event of a Server.
Net.Socket event in Node.js
net.Socket is an eventEmitter and it generates the following events.
Stt Events & Description1 lookupIt happened after resolve a hostname but before connecting 2 connect
Occurs when a Socket connection is successfully established 3 data
Occurs when data has been received. The data parameter will be a Buffer or a String. The encoding part of the data is set by socket.setEncoding (). 4 errors
Occurs when any errors occur. The 'close' event will be called directly after the event. 5 close
Occurs when Socket is closed.
Net.Socket property in Node.js
net.Socket has many useful properties to help you better control interacting with Socket.
Socket.bufferSize1 and Description1This attribute indicates the number of 2 socket.remoteAddress characters that have been padded
Represent the string of the Remote IP address. 3 socket.remoteFamily
Sequence of Remote IP Family. That is 'IPv4' or 'IPv6'. 4 socket.remotePort
Digital representation of Remote Port. For example 80 or 21. 5 socket.localAddress
Represents the string of the Local IP address that a Remote Client connects to. For example, if you are listening on '0.0.0.0' and the Client connects on '192.168.1.1', the value will be '192.168.1.1'. 6 socket.localPort
Digital representation of Local Port. For example, 80 or 21. 7 socket.bytesRead
Number of bytes received. 8 socket.bytesWritten
Number of bytes sent.
Net.Socket method in Node.js
Method & Description1 new net.Socket ([options])Build a new Socket object. 2 socket.connect (port [, host] [, connectListener])
Open the connection for a given Socket. If you provide two port and host parameters, then the Socket will be opened as a TCP Socket. If you do not provide a host, the default value is localhost. If you provide path parameters, the Socket will be opened as a Unix Socket to that path. Socket.connect 3 (path [, connectListener])
Open the connection for a given Socket. If you provide two port and host parameters, then the Socket will be opened as a TCP Socket. If you do not provide a host, the default value is localhost. If you provide path parameters, the Socket will be opened as a Unix Socket to that path. 4 socket.setEncoding ([encoding])
Set up encoding encoding for Socket as a Readable Stream. 5 socket.write (data [, encoding] [, callback])
Sending data on Socket. The second parameter determines the encoding in the case of string data. The default encoding is UTF8. 6 socket.destroy ()
Ensure that there is not any I / O activity happening on this Socket. This method is only needed when an error occurs. 7 socket.pause ()
Temporarily stop reading data. Therefore the 'data' event cannot generate 8 socket.resume ().
Continue reading data after pausing with the pause () method.
For example
Below is an example to illustrate some methods and properties of net Module in Node.js.
Create server.js with content:
var net = require ( 'net' ); var server = net . createServer ( function ( connection ) { console . log ( 'Client connection ' ); connection . on ( 'end' , function () { console . log ( 'Client login ' ); }); connection . ( 'Hello World! Rn' ); connection . Pipe ( connection ); }); server . listen ( 8080 , function () { console . log ( 'Server dang lang' ); });
Run server.js to see the result:
$ node server . js
Check the result.
Server is listening
Next, create client.js as shown below
var net = require ( 'net' ); var client = net . connect ({ port : 8080 }, function () { console . log ( 'Da ket noi elephant Server!' ); }); client . on ( 'data' , function ( data ) { console . log ( data . toString ()); client . end (); }); client . on ( 'end' , function () { console . log ( 'Mat server and server' ); });
Run client.js on another terminal screen to see the result:
$ node client . js
Check the result.
Da ket noi Server!
Hello World!
Please contact the server Elephant
Check the results on the Terminal screen running server.js:
Server is listening
Ket said the Client
Please contact Client
4. DNS Module in Node.js
dns Module in Node.js is used to perform DNS Lookup. The module provides an asynchronous Network Wrapper and can be imported with syntax.
var dns = require ( "dns" )
Method of dns Module in Node.js
Method & Description1 dns.lookup (hostname [, options], callback)Resolve a hostname (eg 'google.com') into A record (IPv4) or AAAA (IPv6) first found. The options parameter can be an object or an integer. If you do not provide the options parameter, then IP v4 and v6 addresses are valid. If options are an integer, then it must be 4 or 6. dns.lookupService (address, port, callback)
Resolve a given address and port into a 3 dns.resolve hostname (hostname [, rrtype], callback)
Resolve a hostname (eg 'google.com') into an array of record types defined by the rrtype parameter. 4 dns.resolve4 (hostname, callback)
Like dns.resolve (), but only for IPv4 queries (a query A). 5 dns.resolve6 (hostname, callback)
Like dns.resolve4 (), but only for queries (an AAAA query). 6 dns.resolveMx (hostname, callback)
Like dns.resolve (), but only for Mail Exchange queries. 7 dns.resolveTxt (hostname, callback)
Like dns.resolve (), but only for Text queries 8 dns.resolveSrv (hostname, callback)
Like dns.resolve (), but only for SRV 9 dns.resolve queries (hostname, callback)
Like dns.resolve (), but only for SOA queries 10 dns.resolveNs (hostname, callback)
Like dns.resolve (), but only for NS 11 queries dns.resolveCname (hostname, callback)
Like dns.resolve (), but only for CNAME 12 dns.reverse (ip, callback)
Reverse resolving an IP address into an array of hostnames
The rrtype value of the dns Module in Node.sj
The list below lists the rrtypes values used by the dns.resolve () method:
A - The default value is IPV4 addresses
AAAA - IPV6 addresses
MX - Mail Exchange logs
TXT - Text records
SRV - Records of SRV
PTR - Used to reverse IP Lookup
NS - Records of Name Server
CNAME - Records about Canonical Name
SOA - stands for Start of Authority Record
Some Error Code of dns Module in Node.js
Each DNS trace can return one of the following Error Code:
dns.NODATA - The DNS Server returns a response that does not include any data.
dns.FORMERR - DNS Server notifies wrong format query.
dns.SERVFAIL - DNS Server returns a common error.
dns.NOTFOUND - Domain name not found.
dns.NOTIMP - DNS Server does not implement request activity.
dns.REFUSED - The DNS Server rejects the query.
dns.BADQUERY - Wrong format query.
dns.BADNAME - Hostname wrong format.
dns.BADFAMILY - Address Family is not supported.
dns.BADRESP - Feedback from DNS is incorrect.
dns.CONNREFUSED - Cannot connect to DNS Server.
dns.TIMEOUT - Timeout while connecting to the DNS Server.
dns.EOF - Short of End of file.
dns.FILE - An error occurred while reading the file.
dns.NOMEM - Out of memory.
dns.DESTRUCTION - Channel is being canceled.
dns.BADSTR - Wrong format string.
dns.BADFLAGS - The flags are invalid.
dns.NONAME - Hostname is not in digital form.
For example
The following example illustrates some methods of dns Module in Node.js. You create main.js with the following content:
var dns = require ( 'dns' ); dns . lookup ( 'www.google.com' , function onLookup ( err , address , family ) { console . log ( 'Dia chi:' , address ); dns . reverse ( address , function ( err , hostnames ) { if ( err ) { console . log ( err . stack ); } console . log ( 'Method of REVERSE for dia:' + address + 'bar with hostname:' + JSON . stringify ( hostnames )); }); });
Run main.js to see the result ::
$ node main . js
Check the result:
Dia spent: 173.194.46.83
Method of REVERSE for branch 173,194.46.83 bar with hostname: ["ord08s11-in-f19.1e100.net"]
5. Domain Module in Node.js
The Module domain in Node.js is used to intervene unresolved errors. These errors can be interfered by using Internal Binding or External Binding.
Internal Binding - Error Emmitter is executing its code inside a Domain's run method.
External Binding - Error Emmitter is added to a Domain using the add method.
To use the Module domain in Node.js, you need to import the following syntax.
var domain = require ( "domain" )
The Domain class of the Domain Module is used to provide functionality to route Error and Exception to a Domain object. This class is the subclass of the EventEmitter class. This Domain class handles errors that it captures and listens for its error events. This object can be created by syntax:
var domain = require ( "domain" ); var child = domain . create ();
Method of the Domain Module in Node.js
Stt Method & Description1 domain.run (function)Run the function function in the domain context, bind all low-level Event Emitter, Timer, and Requests that were created in that context. This is the most basic way to use a domain. 2 domain.add (emitter)
Add Emitter to the domain. If there is any Event Handler called by an Emitter that throws an Error, it will be routed to the domain's error event. 3 domain.remove (emitter)
Contrary to the domain.add (emitter) method. Delete certain Emitter from the domain. 4 domain.exit ()
Exit the current domain
Properties of the Domain Module in Node.js
domain.members: An array of Timer and Event Emitter has been added to the domain.
For example
The following example illustrates some methods of the Domain Module in Node.js. You create main.js with the following content:
var EventEmitter = require ( "events" ). EventEmitter ; var domain = require ( "domain" ); var emitter1 = new EventEmitter (); // Create a domain to use the software to create () var domain1 = domain . create (); domain1 . on ( 'error' , function ( err ) { console . log ( "domain1 will be released: (" + err . message + ")" ); }); // I have an Emitter with a domain name to add () domain1 . add ( emitter1 ); emitter1 . on ( 'error' , function ( err ) { console . log ( "listener se xu ly: (" + err . message + ")" ); }); emitter1 . emit ( 'error' , new Error ( ' Error listener' ); emitter1 . removeAllListeners ( 'error' ); emitter1 . emit ( 'error' , new Error ( 'Duoc domain1' ); var domain2 = domain . create (); domain2 . on ( 'error' , function ( err ) { console . log ( "domain2 will be free: (" + err . message + ")" ); }); / / I have an emitter with domain name to run () domain2 . run ( function () { var emitter2 = new EventEmitter (); emitter2 . emit ( 'error' , new Error ( 'Duoc domain2' )); }); domain1 . remove ( emitter1 ); emitter1 . emit ( 'error' , new Error ( 'Exception'. He thong bi pha vo! ' ));
Run main.js to see the result ::
$ node main . js
Check the result:
listener will be free: (Listener listener)
domain1 will make a difference: (Can I use domain1)
domain2 will earn a lot of money: (Can not use domain2)
events.js: 72
throw er; // Unhandled 'error' event
^
Error: Exception. He is bouncing!
at Object. (/web/com/1427722220_30772/main.js:40:24)
at Module._compile (module.js: 456: 26)
at Object.Module._extensions.js (module.js: 474: 10)
at Module.load (module.js: 356: 32)
at Function.Module._load (module.js: 312: 12)
at Function.Module.runMain (module.js: 497: 10)
at startup (node.js: 119: 16)
at node.js: 906: 3
According to Tutorialspoint
Last lesson: Global objects in Node.js
Next lesson: Web Module in Node.js
You should read it
- Module in Node.js
- Read the File record in Node.js
- Web Module in Node.js
- Schema validation in Node.js using Joi
- Instructions for installing Node.js
- Event Loop in Node.js
- Concept of Buffer in Node.js
- What is Node.js?
- REPL Terminal in Node.js
- NPM in Node.js
- 10 things not to do when running Node.js application
- Hello World program in Node.js
Maybe you are interested
How to fix print streaks, wrong colors on Canon color inkjet printers 'Detox' Facebook in a scientific way Pomodoro 'tomato' method: Working focused, highly effective without fatigue UFOs found in Russia also contain 'bodies of aliens'? Google Maps detects 8 strange bases of aliens? Journey to find gravitational waves and unprecedented world discoveries