Utility : Utility tools

更新时间:
2024-05-13
下载文档

Utility : Utility tools

This module is a common utility function library.

User can use the following code to import the util module.

var util = require('util');

Support

The following shows util module APIs available for each permissions.

 User ModePrivilege Mode
util.isNull
util.isUndefined
util.isNullOrUndefined
util.isNumber
util.isFinite
util.isBoolean
util.isString
util.isObject
util.isFunction
util.isPrimitive
util.isRegExp
util.isBuffer
util.isArray
util.isDate
util.isError
util.isSymbol
util.isPromise
util.inspect
util.inherits
util.clone
util.mixin
util.fillup
util.update
util.different
util.format
util.log
util.logToString
util.promisify

Util Functions

util.isNull(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is null.

Returns true if the given value is strictly null. Otherwise, returns false.

Example

var obj1 = new Buffer(10);
var obj2 = null;

util.isNull(obj1);
// false

util.isNull(obj2);
// true

util.isUndefined(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is undefined.

Returns true if the given value is undefined. Otherwise, returns false.

util.isNullOrUndefined(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is null or undefined.

Returns true if the given value is null or undefined. Otherwise, returns false.

util.isNumber(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Number.

Returns true if the given value is a Number. Otherwise, returns false.

util.isInteger(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Integer.

Returns true if the given value is a Integer. Otherwise, returns false.

util.isFinite(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is a finite number.

Returns true if the given value is a finite number. Otherwise, returns false.

util.isBoolean(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Boolean.

Returns true if the given value is a Boolean. Otherwise, returns false.

util.isString(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is String.

Returns true if the given value is a String. Otherwise, returns false.

util.isObject(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Object.

Returns true if the given value is a Object. Otherwise, returns false.

util.isFunction(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Function.

Returns true if the given value is a Function. Otherwise, returns false.

util.isPrimitive(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value a primitive type.

Returns true if the given value is a primitive type. Otherwise, returns false.

util.isRegExp(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is RegExp.

Returns true if the given value is a RegExp. Otherwise, returns false.

util.isBuffer(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Buffer.

Returns true if the given value is a Buffer. Otherwise, returns false.

util.isArray(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Array.

Returns true if the given value is a Array. Otherwise, returns false.

util.isDate(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Date object.

Returns true if the given value is a Date object. Otherwise, returns false.

util.isError(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Error object.

Returns true if the given value is a Error object. Otherwise, returns false.

util.isSymbol(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Symbol.

Returns true if the given value is a Symbol. Otherwise, returns false.

util.isPromise(value)

  • value {Any} Any value.
  • Returns: {Boolean} Is the specified value is Promise object.

Returns true if the given value is a Promise object. Otherwise, returns false.

util.inspect(obj[, showHidden[, depth]])

  • obj {Any} Any JavaScript primitive or Object.
  • showHidden {Boolean} If true, the obj's non-enumerable symbols and properties will be included in the formatted result as well as WeakMap and WeakSet entries. default: false.
  • depth {Number} Specifies the number of times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse up to the maximum call stack size pass Infinity or null. default: 2.
  • Returns: {String} The representation of passed object.

The util.inspect() method returns a string representation of object that is intended for debugging. The output of util.inspect() may change at any time and should not be depended upon programmatically.

util.inspect.custom

  • Returns: {Symbol} That can be used to declare custom inspect functions.

In addition to being accessible through util.inspect.custom, this symbol is registered globally and can be accessed in any environment as Symbol.for('jsre.util.inspect.custom').

Example

var inspect = Symbol.for('jsre.util.inspect.custom');

class Password {
  constructor(value) {
    this.value = value;
  }

  toString() {
    return 'xxxxxxxx';
  }

  [inspect]() {
    return `Password <${this.toString()}>`;
  }
}

var password = new Password('r0sebud');
console.log(password);
// Prints Password <xxxxxxxx>

util.clone(obj)

  • obj {Object} Source object.
  • Returns: {Object} A cloned object.

Recursively clones all the properties of an obj and references all methods. Return a new object.

Example

var obj1 = { a: 3, b: 5 };
var obj2 = obj1;
var obj3 = util.clone(obj1);

obj1.a = 4;
obj1.b = 6;

console.inspectEnable = true;
console.log(obj1);
console.log(obj2);
console.log(obj3);

util.mixin(target, ...source)

  • target {Object} Target object.
  • source {Object} Source object.
  • Returns: {Object} Target object.

Mixin all source object properties and methods to the target object.

Example

var obj1 = { a: 3, b: 5 };
var obj2 = { c: 3, d: 5 };
var obj3 = { e: 3, f: 5 };

util.mixin(obj3, obj2, obj1);

console.inspectEnable = true;
console.log(obj3);

util.fillup(target, ...source)

  • target {Object} Target object.
  • source {Object} Source object.

When the target object does not have the attributes of the source, complete them, the same attributes will not change.

This method is particularly suitable for: using the default template object to complete a new object with some content.

Example

var obj1 = { a: 3, b: 5 };
var obj2 = { a: 4, d: 6 };

util.fillup(obj1, obj2);

console.inspectEnable = true;
console.log(obj1);

util.update(target, ...source)

  • target {Object} Target object.
  • source {Object} Source object.

Replace the existing contents of the target with the contents of the source.

This method is particularly suitable for: Replace the old configuration with a new one.

Example

var obj1 = { a: 3, b: 5 };
var obj2 = { a: 4, d: 6 };

util.update(obj1, obj2);

console.inspectEnable = true;
console.log(obj1);

util.different(target, source)

  • target {Object} Target object.
  • source {Object} Source object.
  • Returns: {Boolean} Different(true) or same(false).

Compare target and source objects and return compare result.

Example

var obj1 = { a: 3, b: 5, c: 7 };
var obj2 = { a: 2, b: 5, d: 6 };

console.log(util.different(obj1, obj2));

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

  • formatString {String} Format string.
  • Returns: {String} The formatted string.

The util.format() method returns a formatted string using the first argument as a printf-like format.

The first argument is a string containing zero or more placeholder tokens. Each placeholder token is replaced with the converted value from the corresponding argument. Supported placeholders are:

  • %s - String.
  • %d - Number.
  • %j - JSON. Replaced with the string '[Circular]' if the argument contains circular references.
  • %% - Single percent sign ('%'). This does not consume an argument.
  • %x - Hex (%X upper case). EdgerOS 1.6.0 and later versions support.

Example

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

util.log(string[, ...args])

  • string {String} Log message string.

The util.log() method prints the given string to stdout with an included timestamp.

Example

util.log('Timestamped message.');

util.logToString(string[, ...args])

  • string {String} Log format string.
  • Returns: {String} The formatted log string.

The util.logToString() method make the given string to a log string with an included timestamp.

Example

var str = util.logToString('Timestamped message.');

util.promisify(original)

  • original {Function} Original function.
  • Returns: {Function} A version that returns promises.

Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises.

Example

var Device = require('device');

var list = util.promisify(Device.list);
list(true).then(array => {
  // Do something with `array`
}).catch(error => {
  // Handle the error.
});

Or, equivalently using async function:

var Device = require('device');

var list = util.promisify(Device.list);

async function callList() {
  var array = await list(true);
  console.log('Total joined device:', array.length);
}

promisify() assumes that original is a function taking a callback as its final argument in all cases. If original is not a function, promisify() will throw an error. If original is a function but its last argument is not an error-first callback, it will still be passed an error-first callback as its last argument.

Using promisify() on class methods or other methods that use this may not work as expected unless handled specially:

Example

class Foo {
  constructor() {
    this.a = 42;
  }

  bar(callback) {
    callback(null, this.a);
  }
}

var foo = new Foo();

var naiveBar = util.promisify(foo.bar);
// TypeError: Cannot read property 'a' of undefined
// naiveBar().then(a => console.log(a));

naiveBar.call(foo).then((a) => console.log(a)); // '42'

var bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'
文档内容是否对您有所帮助?
有帮助
没帮助