Util: различия между версиями

Материал из support.qbpro.ru
imported>Supportadmin
imported>Supportadmin
 
(не показаны 3 промежуточные версии этого же участника)
Строка 2: Строка 2:


==util.format(format, [...])==
==util.format(format, [...])==
ВозвращаетReturns a formatted string using the first argument as a printf-like format.
Возвращает форматированную по шаблон строку, используя в качестве первого аргумента шаблон в стиле printf (см. язык С).


The first argument is a string that contains zero or more placeholders. Each placeholder is replaced with the converted value from its corresponding argument. Supported placeholders are:
Первый аргумент строка, содержащая ноль или более placeholders. Каждый placeholder заменяется конвертированным значением из переданных аргументов. Поддерживаются следующие placeholders:


*%s - String.
*%s - Строка.
*%d - Number (both integer and float).
*%d - Число (integer или float).
*%j - JSON.
*%j - JSON.
*% - single percent sign ('%'). This does not consume an argument.
*% - single percent sign ('%'). This does not consume an argument.
If the placeholder does not have a corresponding argument, the placeholder is not replaced.
Если для placeholder нет соответствующего аргумента, placeholder не заменяется.


  <nowiki>util.format('%s:%s', 'foo'); // 'foo:%s'</nowiki>
  <nowiki>util.format('%s:%s', 'foo'); // 'foo:%s'</nowiki>
If there are more arguments than placeholders, the extra arguments are converted to strings with util.inspect() and these strings are concatenated, delimited by a space.
Если число аргументов больше количесвта placeholder, лишние аргументы будут преобразованы с помощью util.inspect() и объединены в строку, разделённые пробелом.


  <nowiki>util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'</nowiki>
  <nowiki>util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'</nowiki>
If the first argument is not a format string then util.format() returns a string that is the concatenation of all its arguments separated by spaces. Each argument is converted to a string with util.inspect().
Если первый аргумент не строка, тогда util.format() вернет строку из аргументов, разделенных пробелами. Каждый из аргументов будет конвертирован с помощью util.inspect().


  <nowiki>util.format(1, 2, 3); // '1 2 3'</nowiki>
  <nowiki>util.format(1, 2, 3); // '1 2 3'</nowiki>


==util.debug(string)==
==util.debug(string)==
A synchronous output function. Will block the process and output string immediately to stderr.
Синхронная функция вывода. Процесс будет блокирован и string будет незамедлительно выведена в stderr.


require('util').debug('message on stderr');
require('util').debug('message on stderr');
==util.error([...])==
==util.error([...])==
Same as util.debug() except this will output all arguments immediately to stderr.
Same as util.debug() except this will output all arguments immediately to stderr.
Строка 38: Строка 39:
require('util').log('Timestamped message.');
require('util').log('Timestamped message.');
==util.inspect(object, [options])==
==util.inspect(object, [options])==
Return a string representation of object, which is useful for debugging.
Возвращает object, представленный в виде строки, очень полезно при отладке.


An optional options object may be passed that alters certain aspects of the formatted string:
Необязательные параметры задают различные параметры формирования строки:


*showHidden - if true then the object's non-enumerable properties will be shown too. Defaults to false.
*showHidden - if true then the object's non-enumerable properties will be shown too. Defaults to false.
Строка 70: Строка 71:
util.inspect(obj);
util.inspect(obj);
   // "{nate}"</nowiki>
   // "{nate}"</nowiki>
==util.isArray(object)==
==util.isArray(object)==
Returns true if the given "object" is an Array. false otherwise.
Returns true if the given "object" is an Array. false otherwise.
Строка 122: Строка 124:


==util.inherits(constructor, superConstructor)==
==util.inherits(constructor, superConstructor)==
Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.
Наследует методы прототипа конструктора объекта в другой объект. Прототип конструктора будет установлен для нового объекта, созданного через superConstructor.


As an additional convenience, superConstructor will be accessible through the constructor.super_ property.
As an additional convenience, superConstructor will be accessible through the constructor.super_ property.

Текущая версия от 10:36, 25 августа 2013

These functions are in the module 'util'. Use require('util') to access them.

util.format(format, [...])

Возвращает форматированную по шаблон строку, используя в качестве первого аргумента шаблон в стиле printf (см. язык С).

Первый аргумент строка, содержащая ноль или более placeholders. Каждый placeholder заменяется конвертированным значением из переданных аргументов. Поддерживаются следующие placeholders:

  • %s - Строка.
  • %d - Число (integer или float).
  • %j - JSON.
  • % - single percent sign ('%'). This does not consume an argument.

Если для placeholder нет соответствующего аргумента, placeholder не заменяется.

util.format('%s:%s', 'foo'); // 'foo:%s'

Если число аргументов больше количесвта placeholder, лишние аргументы будут преобразованы с помощью util.inspect() и объединены в строку, разделённые пробелом.

util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'

Если первый аргумент не строка, тогда util.format() вернет строку из аргументов, разделенных пробелами. Каждый из аргументов будет конвертирован с помощью util.inspect().

util.format(1, 2, 3); // '1 2 3'

util.debug(string)

Синхронная функция вывода. Процесс будет блокирован и string будет незамедлительно выведена в stderr.

require('util').debug('message on stderr');

util.error([...])

Same as util.debug() except this will output all arguments immediately to stderr.

util.puts([...])

A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.

util.print([...])

A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

util.log(string)

Output with timestamp on stdout.

require('util').log('Timestamped message.');

util.inspect(object, [options])

Возвращает object, представленный в виде строки, очень полезно при отладке.

Необязательные параметры задают различные параметры формирования строки:

  • showHidden - if true then the object's non-enumerable properties will be shown too. Defaults to false.
  • depth - tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated *objects. Defaults to 2. To make it recurse indefinitely pass null.
  • colors - if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable, see below.
  • customInspect - if false, then custom inspect() functions defined on the objects being inspected won't be called. Defaults to true.

Example of inspecting all properties of the util object:

var util = require('util');

console.log(util.inspect(util, { showHidden: true, depth: null }));

Customizing util.inspect colors

Color output (if enabled) of util.inspect is customizable globally via util.inspect.styles and util.inspect.colors objects.

util.inspect.styles is a map assigning each style a color from util.inspect.colors. Highlighted styles and their default values are: number (yellow) boolean (yellow) string (green) date (magenta) regexp (red) null (bold) undefined (grey) special - only function at this time (cyan) * name (intentionally no styling)

Predefined color codes are: white, grey, black, blue, cyan, green, magenta, red and yellow. There are also bold, italic, underline and inverse codes.

Objects also may define their own inspect(depth) function which util.inspect() will invoke and use the result of when inspecting the object:

var util = require('util');

var obj = { name: 'nate' };
obj.inspect = function(depth) {
  return '{' + this.name + '}';
};

util.inspect(obj);
  // "{nate}"

util.isArray(object)

Returns true if the given "object" is an Array. false otherwise.

var util = require('util');

util.isArray([])
  // true
util.isArray(new Array)
  // true
util.isArray({})
  // false

util.isRegExp(object)

Returns true if the given "object" is a RegExp. false otherwise.

var util = require('util');

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

util.isDate(object)

Returns true if the given "object" is a Date. false otherwise.

var util = require('util');

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

util.isError(object)

Returns true if the given "object" is an Error. false otherwise.

var util = require('util');

util.isError(new Error())
  // true
util.isError(new TypeError())
  // true
util.isError({ name: 'Error', message: 'an error occurred' })
  // false

Не используется util.pump(readableStream, writableStream, [callback])

Stability: 0 - Deprecated:

ВЗАМЕН ИСПОЛЬЗОВАТЬ readableStream.pipe(writableStream)

Read the data from readableStream and send it to the writableStream. When writableStream.write(data) returns false readableStream will be paused until the drain event occurs on the writableStream. callback gets an error as its only argument and is called when writableStream is closed or when an error occurs.

util.inherits(constructor, superConstructor)

Наследует методы прототипа конструктора объекта в другой объект. Прототип конструктора будет установлен для нового объекта, созданного через superConstructor.

As an additional convenience, superConstructor will be accessible through the constructor.super_ property.

var util = require("util");
var events = require("events");

function MyStream() {
    events.EventEmitter.call(this);
}

util.inherits(MyStream, events.EventEmitter);

MyStream.prototype.write = function(data) {
    this.emit("data", data);
}

var stream = new MyStream();

console.log(stream instanceof events.EventEmitter); // true
console.log(MyStream.super_ === events.EventEmitter); // true

stream.on("data", function(data) {
    console.log('Received data: "' + data + '"');
})
stream.write("It works!"); // Received data: "It works!"