May 10, 2021 Node.js
5. util.inspect(object[, options])
10.. util.inherits(constructor, superConstructor)
稳定性: 4 - 锁定
This section describes the .js
'util'
module of the Node module, accessing the module through
require('util')
as follows:
const util = require('util');
util
module was originally designed to support the .js the Node module. M
any of the functions here are very useful for your program. I
f you feel that these functions do not meet your requirements, you can write your own tool functions.
We
'util'
module to add extensions that are useless for node internal functions.
section
is debugged in the program node section
The function used to create a conditional write to stderr (based on
NODE_DEBUG
variable). I
f
section
in an environment variable, the return function will be
console.error()
Otherwise, an empty function is returned.
For example:
javascript
var debuglog = util.debuglog('foo');
var bar = 123;
debuglog('hello from foo [%d]', bar);
If the program runs
NODE_DEBUG=foo
it will output:
FOO 3245: hello from foo [123]
3245
the process ID.
If you do not run in this environment variable, nothing will be printed.
You can use commas to
NODE_DEBUG
variables.
For
NODE_DEBUG=fs,net,tls
Use the first argument to return a formatted string, similar to
printf
The first argument is a string that contains 0 or more placeholders. E ach placeholder is replaced with the value that you want the argument to convert. Supported placeholders include:
%s
- String.
%d
- Numbers (integers and floats).
%j
- JSON。
If the argument contains a circular reference, R is replaced with a string
%%
- A single percent sign
'%'
Does not consume a parameter.
If the placeholder does not contain a corresponding parameter, the placeholder is not replaced.
util.format('%s:%s', 'foo'); // 'foo:%s'
If the argument exceeds the placeholder, the extra argument is converted to a string by
util.inspect()
and stitched together, separated by spaces.
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
If the first argument is not a formatted
util.format()
a string (space split) stitched together by all parameters.
Each parameter is converted
util.inspect()
util.format(1, 2, 3); // '1 2 3'
Output
stdout
with time stamp:
require('util').log('Timestamped message.');
Returns a string representation of an object, which is useful when code debugging.
Change the formatting output of an object by adding some optional options:
showHidden
- If true, the
true
non-enumerateable properties are displayed.
The default is
false
depth
- Tells
inspect
times to format the object. T
his is useful when formatting large and complex objects. T
he default
2
If you want infinite recursion,
null
colors
- If
true
the output is formatted as colored code.
The default is
false
the color can be customized, see below.
customInspect
- If
false
the aspect (depth, opts) method defined on the object being examined will not be called.
True by default.
An example
util
all properties on a util object:
var util = require('util');
console.log(util.inspect(util, { showHidden: true, depth: null }));
When called, parameter values can provide their own custom insight (depth, opts) methods. The method receives the current recursive check depth, as well as other parameters passed in to util.inspect().
util.inspect
color
util.inspect
util.inspect.styles
util.inspect.colors
objects.
util.inspect.styles
util.inspect.colors
a pair of mappings of style colors.
Highlight styles and their defaults:
数字
(yellow)
boolean
(yellow)
字符串
(green)
date
(magentia)
regexp
(red)
null
(bold)
undefined
(italic)
special
(turquoise)
name
(internal, not style)
黄色
Predefined colors
white
斜体
black
红色
blue
cyan
绿色
magenta,
洋红
red, and
粗体
斜体
下划线
and
反选
styles.
inspect()
function
The object can also
inspect(depth)
and when you examine the object using util.inspect(), the object-customized check method is performed:
var util = require('util');
var obj = { name: 'nate' };
obj.inspect = function(depth) {
return '{' + this.name + '}';
};
util.inspect(obj);
// "{nate}"
You can return another object, and the returned string is formatted according to the returned object. T
his is
JSON.stringify()
workflow. Y
ou can also return another object completely, and the returned string is formatted according to the returned object.
This is
JSON.stringify()
works:
var obj = { foo: 'this will not show up in the inspect() output' };
obj.inspect = function(depth) {
return { bar: 'baz' };
};
util.inspect(obj);
// "{ bar: 'baz' }"
Array.isArray's internal alias.
If the parameter "object" is an array, return
true
otherwise return
false
var util = require('util');
util.isArray([])
// true
util.isArray(new Array)
// true
util.isArray({})
// false
If the parameter "object" is
RegExp
true
otherwise false is
false
var util = require('util');
util.isRegExp(/some regexp/)
// true
util.isRegExp(new RegExp('another regexp'))
// true
util.isRegExp({})
// false
If the argument "object" is
Date
otherwise false is
false
true
var util = require('util');
util.isDate(new Date())
// true
util.isDate(Date())
// false (without 'new' returns a String)
util.isDate({})
// false
If the argument "object" is
Error
otherwise false is
false
true
var util = require('util');
util.isError(new Error())
// true
util.isError(new TypeError())
// true
util.isError({ name: 'Error', message: 'an error occurred' })
// false
Inherit the prototype method
from one constructor
constructor to another.
The prototype of the constructor is set to a new object
superConstructor
class.
constructor.super_
the
superConstructor
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!"
Indicate that the method is no 1 2st.
exports.puts = exports.deprecate(function() {
for (var i = 0, len = arguments.length; i < len; ++i) {
process.stdout.write(arguments[i] + '\n');
}
}, 'util.puts: Use console.log instead')
Returns a modified function that is warned only once by default. I
f you set
--no-deprecation
the function does nothing.
If you set
--throw-deprecation
if you use the API app, you throw an exception.
稳定性: 0 - 抛弃: 使用 console.error() 替换。
console.error
稳定性: 0 - 抛弃: 使用 console.error() 替换。
console.error
稳定性: 0 - 抛弃:使用 console.log() 替换。
console.log
predecessor.
稳定性: 0 - 抛弃: 使用 console.log() 替换。
console.log
predecessor.
稳定性: 0 - 抛弃: Use readableStream.pipe(writableStream)
stream.pipe