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

Tutorial Básico NodeJS

Express.js NodeJS

Buffer & URL NodeJS

MySql NodeJS

MongoDB NodeJS

Arquivos NodeJS (FS)

Outros NodeJS

Ferramentas Comuns do Node.js

O util é um módulo nuclear do Node.js, que fornece uma coleção de funções comuns, usadas para compensar a insuficiência de funcionalidades do JavaScript nuclear.

O método de uso é o seguinte:

const util = require('util');

util.callbackify

util.callbackify(original) transforma funções assíncronas (ou funções que retornam Promise) em funções de estilo de callback que seguem a prioridade de exceções, por exemplo, (err, value) => ... como último parâmetro. Na função de callback, o primeiro parâmetro é a razão de rejeição (se a Promise for resolvida, então null), e o segundo parâmetro é o valor resolvido.

Exemplo Online

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);
});

O resultado da saída do código acima é:

hello world

As funções de callback são executadas de forma assíncrona e têm rastreamento de erros de pilha. Se a função de callback lançar uma exceção, o processo desencadeará uma exceção 'uncaughtException', e se não for capturada, o processo sairá.

null tem um significado especial como parâmetro em funções de callback, se o primeiro parâmetro da função de callback for a razão de rejeição da Promise e tiver um valor de retorno que possa ser convertido em falso, esse valor será encapsulado em um objeto Error e pode ser obtido através da propriedade reason.

function fn() {
  return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {}}
  // Quando um Promise é rejeitado com um `null`, ele é empacotado como um Error e o valor original é armazenado em `reason`.
  err && err.hasOwnProperty('reason') && err.reason === null;  // true
});

original é uma função assíncrona. Esta função retorna uma função de callback convencional.

util.inherits

util.inherits(constructor, superConstructor) é uma função que implementa a herança de protótipos entre objetos.

As características orientadas a objetos do JavaScript são baseadas em protótipos, diferindo das comuns baseadas em classes. O JavaScript não fornece uma característica de nível de linguagem para a herança de objetos, mas é implementado através de cópia de protótipos.

Aqui vamos apresentar o uso de util.inherits, como exemplo:

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);

Nós definimos um objeto básico Base e um Sub que herda de Base, o Base possui três atributos definidos no construtor e uma função definida no prototype, a herança é implementada através de util.inherits. O resultado da execução é o seguinte:

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

Note:Sub only inherits the functions 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, that 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 layers, if the object is very complex, you can specify the number of layers 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 number of recursive layers. If the value of colors is true, the output format will be in ANSI color encoding, usually used to display more beautiful effects in the terminal.

Especially to point out that util.inspect will not simply convert objects to strings 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));

O resultado da execução é:

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

util.isArray(object)

Se o parâmetro 'object' fornecido for um array, retorna true, caso contrário, retorna false.

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

util.isRegExp(object)

Se o parâmetro 'object' fornecido for uma expressão regular, retorna true, caso contrário, retorna false.

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

util.isDate(object)

Se o parâmetro 'object' fornecido for uma data, retorna true, caso contrário, retorna false.

var util = require('util');
util.isDate(new Date())
  // true
util.isDate(Date())
  // false (sem 'new' retorna uma String)
util.isDate({})
  // false

Mais detalhes podem ser encontrados em http://nodejs.org/api/util.html Conheça o detalhe.