Module util
The util module provides practical tool functions such as judgment of data type, copying of object attributes, parsing of template strings, and event processing.
The following is a specific introduction and examples:
- Determine the data type -
util.is[type]
This module provides methods such asisDate
,isRegExp
,isError
etc. to determine the data type of the incoming parameters, for example:
1
2
3var util = require('util');
console.log(util.isDate(new Date()));
console.log(util.isRegExp(/some regexp/));
- Object property copying -
util.inherits()
This method can optionally inherit one constructor from another, thus implementing prototypal inheritance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16var util = require('util');
function Animal() {
this.name = 'Animal';
this.sleep = function() {
console.log(this.name + '正在睡觉!');
}
}
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};
function Cat() {
this.name = 'cat';
}
util.inherits(Cat, Animal);
Use Cat
this constructor to inherit Animal
the instance properties and prototype properties of , and print Cat
the properties and methods of the instance.
1
2
3
4var cat = new Cat();
console.log(cat.name);
console.log(cat.eat('fish'));
console.log(cat.sleep());
- util.format() Formatted output template
1
2
3
4
5const util = require('util');
const str1 = util.format('%s:%s', 'foo');
const str2 = util.format('%s:%s', 'foo', 'bar', 'baz');
console.log(str1) // => 'foo:%s'
console.log(str2) // => 'foo:bar baz'
The above are util
some common methods of modules, which can often be used to simplify the actual development process.
object
LruCache
LRU (least recently used) cache object, seeLruCacheobject.
1LruCache util.LruCache;
TextDecoder
TextDecoderdecoding object, seeTextDecoderobject.
1TextDecoder util.TextDecoder;
TextEncoder
TextEncoderEncoding objects, seeTextEncoderobject.
1TextEncoder util.TextEncoder;
types
typesThe module provides tool functions for determining data types.
1types util.types;
static function
format
Format variables according to the specified format
1
2static String util.format(String fmt,
...args);
Call parameters:
- fmt: String, format string
- args: ..., optional parameter list
Return results:
- String, returns the formatted string
format format variable
1static String util.format(...args);
Call parameters:
- args: ..., optional parameter list
Return results:
- String, returns the formatted string
inherits
Inherit prototype functions from one constructor to another. The prototype of the constructor will be set to a new object created from the superclass (superConstructor).
1
2static util.inherits(Value constructor,
Value superConstructor);
Call parameters:
- constructor: Value, initial constructor
- superConstructor: Value, the inherited super class
inspect
The function returns the string representation of obj, mainly used for debugging. Additional options can be used to change certain aspects of the formatted string.
1
2static String util.inspect(Value obj,
Object options = {});
Call parameters:
- obj: Value, specifies the object to be processed
- options: Object, specify format control options
Return results:
- String, returns the formatted string
The following parameters are supported:
1
2
3
4
5
6
7
8
9{
"colors": false, // specify if output should be colorized, defaults to false
"depth": 2, // specify the max depth of the output, defaults to 2
"table": false, // specify if output should be a table, defaults to false
"encode_string": true, // specify if string should be encoded, defaults to true
"maxArrayLength": 100, // specify max number of array elements to show, set to 0 or negative to show no elements, defaults to 100
"maxStringLength": 10000, // specify max string length to output, set to 0 or negative to show no strings, defaults to 10000
"fields": [], // specify the fields to be displayed, defaults to all
}
deprecate
Encapsulates the given function. This function is only compatible and does not output warnings.
1
2
3static Function util.deprecate(Function fn,
String msg,
String code = "");
Call parameters:
- fn: Function, given the function that needs to be encapsulated
- msg: String, given warning message
- code: String, given warning number
Return results:
- Function, if the encapsulation result
isEmpty
Checks if the given variable contains no value (no enumerable properties)
1static Boolean util.isEmpty(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if empty
isArray
Checks whether the given variable is an array
1static Boolean util.isArray(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is an array
isBoolean
Tests whether the given variable is a Boolean
1static Boolean util.isBoolean(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is Boolean, it returns True
isNull
Checks whether the given variable is Null
1static Boolean util.isNull(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is Null, it returns True
isNullOrUndefined
Checks whether the given variable is Null or Undefined
1static Boolean util.isNullOrUndefined(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is Null or Undefined, it returns True
isNumber
Tests whether the given variable is a number
1static Boolean util.isNumber(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a number
isBigInt
Tests whether the given variable is a BigInt
1static Boolean util.isBigInt(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a number
isString
Checks whether the given variable is a string
1static Boolean util.isString(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a string
isUndefined
Checks whether the given variable is Undefined
1static Boolean util.isUndefined(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is Undefined, return True
isRegExp
Tests whether the given variable is a regular object
1static Boolean util.isRegExp(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a regular object
isObject
Tests whether the given variable is an object
1static Boolean util.isObject(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is an object
isDate
Tests whether the given variable is a date object
1static Boolean util.isDate(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a date object
isNativeError
Tests whether the given variable is an error object
1static Boolean util.isNativeError(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is an error object
isPrimitive
Checks whether the given variable is of primitive type
1static Boolean util.isPrimitive(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a primitive type
isSymbol
Check whether the given variable is of type Symbol
1static Boolean util.isSymbol(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a Symbol type, it returns True
isDataView
Checks whether the given variable is of type DataView
1static Boolean util.isDataView(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a DataView type, it returns True
isExternal
Checks whether the given variable is of type External
1static Boolean util.isExternal(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is an External type, it returns True
isMap
Check whether the given variable is of type Map
1static Boolean util.isMap(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a Map type, it returns True
isMapIterator
Checks whether the given variable is of type MapIterator
1static Boolean util.isMapIterator(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a MapIterator type
isPromise
Checks whether the given variable is of type Promise
1static Boolean util.isPromise(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a Promise type, it returns True
isAsyncFunction
Checks whether the given variable is of type AsyncFunction
1static Boolean util.isAsyncFunction(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is an AsyncFunction type, it returns True
isSet
Checks whether the given variable is of type Set
1static Boolean util.isSet(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a Set type, it returns True
isSetIterator
Checks whether the given variable is of type SetIterator
1static Boolean util.isSetIterator(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a SetIterator type, it returns True
isTypedArray
Checks whether the given variable is of type TypedArray
1static Boolean util.isTypedArray(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a TypedArray type, it returns True
isUint8Array
Checks whether the given variable is of type Uint8Array
1static Boolean util.isUint8Array(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is Uint8Array type
isFunction
Tests whether the given variable is a function object
1static Boolean util.isFunction(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, returns True if it is a function object
isBuffer
Tests whether the given variable is a functionBufferobject
1static Boolean util.isBuffer(Value v);
Call parameters:
- v: Value, given the variable to be detected
Return results:
- Boolean, if it is a functionBufferObject returns True
isDeepEqual
Test value depth is equal to expected value
1
2static Boolean util.isDeepEqual(Value actual,
Value expected);
Call parameters:
- actual: Value, the value to be tested
- expected: Value, expected value
Return results:
- Boolean, returns True if the depths are equal
has
Query whether the specified object contains the given key
1
2static Boolean util.has(Value v,
String key);
Call parameters:
- v: Value, given the object to be queried
- key: String, specify the key to be queried
Return results:
- Boolean, returns an array of all keys of the object
keys
Query all key arrays of the specified object
1static Array util.keys(Value v);
Call parameters:
- v: Value, given the object to be queried
Return results:
- Array, returns an array of all keys of the object
values
Query all value arrays of the specified object
1static Array util.values(Value v);
Call parameters:
- v: Value, given the object to be queried
Return results:
- Array, returns an array of all values of the object
clone
Clone the given variable, if it is an object or array, copy the contents to the new object
1static Value util.clone(Value v);
Call parameters:
- v: Value, given the variable to be cloned
Return results:
- Value, returns the clone result
deepFreeze
Deep freeze an object. The frozen object and the objects it contains will not be allowed to be modified.
1static util.deepFreeze(Value v);
Call parameters:
- v: Value, specifies the object to be frozen
extend
Extend the key values of one or more objects to the specified object
1
2static Value util.extend(Value v,
...objs);
Call parameters:
- v: Value, specifies the object to be extended
- objs: ..., specifies one or more objects for expansion
Return results:
- Value, returns the expanded result
_extend
Extend the key values of one or more objects to the specified object, which is an alias of extend
1
2static Value util._extend(Value v,
...objs);
Call parameters:
- v: Value, specifies the object to be extended
- objs: ..., specifies one or more objects for expansion
Return results:
- Value, returns the expanded result
pick
Return aobjectCopy, filter out only the attribute values of the specified key
1
2static Object util.pick(Value v,
...objs);
Call parameters:
- v: Value, specifies the object to filter
- objs: ..., specify one or more keys for selection
Return results:
- Object, returns filtered results
omit
Return aobjectCopy, only excluding the attribute value of the specified key
1
2static Object util.omit(Value v,
...keys);
Call parameters:
- v: Value, specifies the object to filter
- keys: ..., specify one or more keys for exclusion
Return results:
- Object, returns excluded results
first
Get the first element of the array
1static Value util.first(Value v);
Call parameters:
- v: Value, given the array to be obtained
Return results:
- Value, returns the retrieved element
Get the first multiple elements of an array
1
2static Value util.first(Value v,
Integer n);
Call parameters:
- v: Value, given the array to be obtained
- n: Integer, specifies the number of elements to be obtained
Return results:
- Value, returns the obtained array of elements
last
Get the last element of the array
1static Value util.last(Value v);
Call parameters:
- v: Value, given the array to be obtained
Return results:
- Value, returns the retrieved element
Get multiple elements at the end of an array
1
2static Value util.last(Value v,
Integer n);
Call parameters:
- v: Value, given the array to be obtained
- n: Integer, specifies the number of elements to be obtained
Return results:
- Value, returns the obtained array of elements
unique
Get a deduplicated copy of the elements of an array
1
2static Array util.unique(Value v,
Boolean sorted = false);
Call parameters:
- v: Value, given the array to be duplicated
- sorted: Boolean, specifies whether the array is sorted. If the array is sorted, a fast algorithm will be used.
Return results:
- Array, returns the array after removing duplicate elements
union
Combine the values of one or more arrays into an array with unique values
1static Array util.union(...arrs);
Call parameters:
- arrs: ..., specify one or more arrays for merging
Return results:
- Array, returns the merged result
intersection
Returns the intersection of the array containing arr excluding one or more array elements.
1static Array util.intersection(...arrs);
Call parameters:
- arrs: ..., specify one or more arrays used to calculate intersection
Return results:
- Array, returns the result of calculating the intersection
flatten
Convert an array with multiple levels of nesting (the nesting can be any number of levels) into an array with only one level. If you pass the shallow parameter, the array will be reduced to only one dimension of nesting.
1
2static Array util.flatten(Value arr,
Boolean shallow = false);
Call parameters:
- arr: Value, specifies the array to be converted
- shallow: Boolean, specifies whether to reduce only one dimension of nesting, the default is false
Return results:
- Array, returns the result of the conversion
without
Returns an array containing one or more elements in the arr array, excluding one or more elements.
1
2static Array util.without(Value arr,
...els);
Call parameters:
- arr: Value, specifies the array to be excluded
- els: ..., specifies one or more elements to exclude
Return results:
- Array, returns excluded results
difference
Returns an array containing the elements in the arr array excluding the without array elements.
1
2static Array util.difference(Array list,
...arrs);
Call parameters:
- list: Array, specifies the array to be excluded
- arrs: ..., specifies one or more arrays to exclude
Return results:
- Array, returns excluded results
each
Traverse all elements in the list and output each element in order. If the context parameter is passed, the iterator is bound to the context object. Each time iterator is called, three parameters are passed: (element, index, list)
1
2
3static Value util.each(Value list,
Function iterator,
Value context = undefined);
Call parameters:
- list: Value, specifies the list or object to be traversed
- iterator: Function, specifies the callback function used for traversal
- context: Value, specifies the context object bound when calling the iterator
Return results:
- Value, returns the list itself
map
Each value in the list is mapped to a new array through a transformation function (iterator). If the context parameter is passed, the iterator is bound to the context object. Each time iterator is called, three parameters are passed: (element, index, list)
1
2
3static Array util.map(Value list,
Function iterator,
Value context = undefined);
Call parameters:
- list: Value, specifies the list or object to be transformed
- iterator: Function, specifies the callback function used for transformation
- context: Value, specifies the context object bound when calling the iterator
Return results:
- Array, returns the result of the transformation
reduce
Reduce the elements in the list to a single value. If the context parameter is passed, the iterator is bound to the context object. Each time iterator is called, three parameters are passed: (memo, element, index, list)
1
2
3
4static Value util.reduce(Value list,
Function iterator,
Value memo,
Value context = undefined);
Call parameters:
- list: Value, specifies the list or object to be summarized
- iterator: Function, specifies the callback function used for resolution
- memo: Value, specifies the initial value of the reduction
- context: Value, specifies the context object bound when calling the iterator
Return results:
- Value, returns the summarized result
parseArgs
Parse the command line string and return the parameter list
1static NArray util.parseArgs(String command);
Call parameters:
- command: String, specifies the command line string to be parsed
Return results:
- NArray, returns the parsed parameter list
compile
Compile script to binary code
1
2
3static Buffer util.compile(String srcname,
String script,
Integer mode = 0);
Call parameters:
- srcname: String, specify the name of the script to be added
- script: String, specifies the script code to be compiled
- mode: Integer, compilation mode, 0: module, 1: script, 2: worker, default is 0
Return results:
- Buffer, returns the compiled binary code
util.compileScripts can be compiled into v8 internal running data blocks (non-machine executable code). The compiled code can be directly loaded and executed by run and require after being saved as *.jsc.
Since after compilation, the target code will not be able to reversely obtain the source code, programs that rely on Function.toString will not run properly.
sync
Wrap callback or async functions to call them synchronously
1
2static Function util.sync(Function func,
Boolean async_func = false);
Call parameters:
- func: Function, given the function that needs to be wrapped
- async_func: Boolean, specifies that func is processed as an async function. If it is false, it will be automatically judged.
Return results:
- Function, returns a function that runs synchronously
util.syncProcess the callback function or async function into a sync function to facilitate calling.
The callback example is as follows:
1
2
3
4
5
6
7
8
9
10
11// callback
var util = require('util');
function cb_test(a, b, cb) {
setTimeout(() => {
cb(null, a + b);
}, 100);
}
var fn_sync = util.sync(cb_test);
console.log(fn_sync(100, 200));
An async example is as follows:
1
2
3
4
5
6
7
8
9// async/await
var util = require('util');
async function async_test(a, b) {
return a + b;
}
var fn_sync = util.sync(async_test);
console.log(fn_sync(100, 200));
For promise-returning functions that are not marked async, sync mode can be specified manually:
1
2
3
4
5
6
7
8
9
10
11// async/await
var util = require('util');
function async_test(a, b) {
return new Promise(function(resolve, reject) {
resolve(a + b);
});
}
var fn_sync = util.sync(async_test, true);
console.log(fn_sync(100, 200));
promisify
Wrap callback function for async call
1static Function util.promisify(Function func);
Call parameters:
- func: Function, given the function that needs to be wrapped
Return results:
- Function, returns async function
util.promisifyProcess the callback function as an async function to facilitate calling.
The callback example is as follows:
1
2
3
4
5
6
7
8
9
10
11// callback
var util = require('util');
function cb_test(a, b, cb) {
setTimeout(() => {
cb(null, a + b);
}, 100);
}
var fn_sync = util.promisify(cb_test);
console.log(async fn_sync(100, 200));
callbackify
Wrap async function for callback call
1static Function util.callbackify(Function func);
Call parameters:
- func: Function, given the function that needs to be wrapped
Return results:
- Function, return callback function
util.callbackifyProcess the async function into a callback function to facilitate calling.
An async example is as follows:
1
2
3
4
5
6
7
8
9
10
11
12// async
var util = require('util');
async function async_test(a, b) {
return a + b;
}
var fn_callback = util.callbackify(async_test);
fn_callback(100, 200, (err, result) => {
console.log(result);
});
buildInfo
Query the current engine and component version information
1static Object util.buildInfo();
Return results:
- Object, returns the component version object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24{
"fibjs": "0.25.0",
"clang": "9.1",
"date": "Jun 12 2018 07:22:40",
"vender": {
"ev": "4.24",
"expat": "2.2.5",
"gd": "2.2.4",
"jpeg": "8.3",
"leveldb": "1.17",
"mongo": "0.7",
"pcre": "8.21",
"png": "1.5.4",
"mbedtls": "2.6.1",
"snappy": "1.1.2",
"sqlite": "3.23.0",
"tiff": "3.9.5",
"uuid": "1.6.2",
"v8": "6.7.288.20",
"v8-snapshot": true,
"zlib": "1.2.7",
"zmq": "3.1"
}
}