English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

Other NodeJS

Node.js Common Tools

Util is a Node.js core module that provides a collection of commonly used functions to supplement the insufficient functionality of core JavaScript.

Usage as follows:

const util = require('util');

util.callbackify

util.callbackify(original) converts an async asynchronous function (or a function that returns a Promise) into a callback-style function that follows exception-first, such as using (err, value) => ... as the last parameter. In the callback function, the first parameter is the reason for the rejection (if the Promise is resolved, it is null), and the second parameter is the resolved value.

Online Example

const util = require('util');
async function fn() {
  return 'hello world';
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});

The output of the above code is as follows:

hello world

Callback functions are executed asynchronously and have exception stack trace tracking. If the callback function throws an exception, the process will trigger an 'uncaughtException' exception, and if it is not caught, the process will exit.

Null has a special meaning as a parameter in callback functions. If the first parameter of the callback function is the reason for the Promise rejection and it has a return value that can be converted to a boolean false, this value will be wrapped in an Error object, and it can be accessed through the property reason.

function fn() {
  return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
  // When a Promise is rejected with `null`, it is wrapped as an Error and the original value is stored in `reason`.
  err && err.hasOwnProperty('reason') && err.reason === null;  // true
});

original is an async asynchronous function. This function returns a traditional callback function.

util.inherits

util.inherits(constructor, superConstructor) is a function that implements prototype inheritance between objects.

JavaScript's object-oriented features are based on prototypes, which is different from the common class-based. JavaScript does not provide language-level features for object inheritance, but achieves it through prototype copying.

Here we only introduce the usage of util.inherits, an example is as follows:

var util = require('util'); 
function Base() { 
    this.name = 'base'; 
    this.base = 1991; 
    this.sayHello = function() { 
    console.log('Hello ') + this.name); 
    }; 
} 
Base.prototype.showName = function() { 
    console.log(this.name);
}; 
function Sub() { 
    this.name = 'sub'; 
} 
util.inherits(Sub, Base); 
var objBase = new Base(); 
objBase.showName(); 
objBase.sayHello(); 
console.log(objBase); 
var objSub = new Sub(); 
objSub.showName(); 
//objSub.sayHello(); 
console.log(objSub);

We define a basic object Base and a Sub that inherits from Base. Base has three properties defined in the constructor and a function defined in the prototype, inheritance is achieved through util.inherits. The running result is as follows:

base 
Hello base 
{ name: 'base', base: 1991, sayHello: [Function] 
sub 
{ name: 'sub' }

Note:Sub only inherits the function defined in the prototype of Base, and the base properties and sayHello function created internally in the constructor are not inherited by Sub.

At the same time, properties defined in the prototype will not be output as object properties by console.log. If we remove the comment from objSub.sayHello(); this line, we will see:

node.js:201 
throw e; // process.nextTick error, or 'error' event on first tick 
^ 
TypeError: Object #<Sub> has no method 'sayHello' 
at Object.<anonymous> (/home/byvoid/utilinherits.js:29:8) 
at Module._compile (module.js:441:26) 
at Object..js (module.js:459:10) 
at Module.load (module.js:348:31) 
at Function._load (module.js:308:12) 
at Array.0 (module.js:479:10) 
at EventEmitter._tickCallback (node.js:192:40)

util.inspect

util.inspect(object,[showHidden],[depth],[colors]) is a method that converts any object to a string, usually used for debugging and error output. It at least accepts one parameter object, which is the object to be converted.

showHidden is an optional parameter. If the value is true, more hidden information will be output.

Depth represents the maximum number of recursive levels. If the object is very complex, you can specify the level to control the amount of output information. If depth is not specified, it will default to recursion 2 The layer, specified as null means that the object will be traversed completely without limit in the recursive level. If the value of colors is true, the output format will be encoded with ANSI color codes, usually used to display more beautiful effects in the terminal.

It should be pointed out that util.inspect will not simply convert an object to a string directly, even if the object defines a toString method, it will not be called.

var util = require('util'); 
function Person() { 
    this.name = 'byvoid'; 
    this.toString = function() { 
    return this.name; 
    }; 
} 
var obj = new Person(); 
console.log(util.inspect(obj)); 
console.log(util.inspect(obj, true));

The running result is:

Person { name: 'byvoid', toString: [Function] }
Person {
  name: 'byvoid',
  toString: 
   { [Function]
     [length]: 0,
     [name]: '',
     [arguments]: null,
     [caller]: null,
     [prototype]: { [constructor]: [Circular] } }

util.isArray(object)

If the given parameter "object" is an array, it returns true; otherwise, it returns false.

var util = require('util');
util.isArray([])
  // true
util.isArray(new Array)
  // true
util.isArray({})
  // false

util.isRegExp(object)

If the given parameter "object" is a regular expression, it returns true; otherwise, it returns false.

var util = require('util');
util.isRegExp(/some regexp/)
  // true
util.isRegExp(new RegExp('another regexp'))
  // true
util.isRegExp({})
  // false

util.isDate(object)

If the given parameter "object" is a date, it returns true; otherwise, it returns false.

var util = require('util');
util.isDate(new Date())
  // true
util.isDate(Date())
  // false (without 'new' returns a String)
util.isDate({})
  // false

For more details, please visit http://nodejs.org/api/util.html Learn more details.