Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the util module in node.js do?

Tags:

node.js

I'm aware of how to include the util module,

var util = require('util');

However what does it mean and what does it do?

Edit Yes, I know about the docs http://nodejs.org/api/util.html However what I want is something of an explanation of when and why I would use the util module..

like image 947
Noel Vock Avatar asked Jun 28 '13 15:06

Noel Vock


People also ask

What does Util format do?

The util. format() method returns a formatted string that will use the first argument as a printf like format string. This format can also contain zero or more format specifiers. These specifiers can be replaced with the converted value from the corresponding argument.

What does Util inspect do?

util. inspect() returns a string representation of the object passed as a parameter and especially comes in handy while working with large complex objects.

What is a utility module?

The utility module contains ora-fn functions for handling strings and dates. These functions are defined in XDK XQuery, whereas the oxh functions are specific to Oracle XQuery for Hadoop. The utility functions are described in the following topics: Duration, Date, and Time Functions.

What do you need to do before using the Util module in your code?

Before logging anything, util. debuglog is called and given a tag corresponding to the module within which it will be used. It then returns a function which can be called to log anything within your application.


1 Answers

The node.js "util" module provides "utility" functions that are potentially helpful to a developer but don't really belong anywhere else. (It is, in fact, a general programming convention to have a module or namespace named "util" for general purpose utility functions.) You would use the functions in the "util" module if you had a need to use any of them.

For example, if you need to test if an arbitrary value is an array you could write your own function or you could use util.isArray(...):

function myIsArray(o) {
  return (typeof(o)==='object') && (o.constructor === Array);
}

// Or...
var util = require('util');
if (util.isArray(someValue)) {
  // ...
}

In general, after reading the documentation for any of the utility functions you can make an assessment about whether or not you could, or would, like to use them in your own program. If you decide that doing so is a good idea then you can do it.

like image 65
maerics Avatar answered Oct 14 '22 11:10

maerics