Node.js – util.formatWithOptions() 方法

该方法的工作方式与该方法相同。两者之间的唯一区别是该方法采用一个inspectOptions参数,该参数指定沿该方法传递的选项。util.formatWithOptions()util.format()formatWithOptions()util.inspect()

语法

util.formatWithOptions(inspectOptions, format, [args])

参数

参数定义如下:

  • inspectOptions -这些选项将用于检查沿此方法传递的对象。

  • format - 此参数接受所传递输入值的格式类型的输入。

示例 1

创建一个名为“ formatWithOptions.js ”的文件并复制以下代码片段。创建文件后,使用命令“ node formatWithOptions.js ”运行此代码。

//Node.jsutil.formatWithOptions() 方法

// 导入 util 模块
const util = require('util');

function fun() {
   // 沿格式传递不同的选项
   var val0 = util.formatWithOptions(
      { depth:0, colors: true },
      'See object %O', { foo: 21 });

   var val1 = util.formatWithOptions(
      { colors: true, showProxy : true },
      '%s:%s:%s', 'a', 'b', 'c');

   var val2 = util.formatWithOptions(
      { showHidden: true, colors: true },
      '%s:%s', 'raj', 'rahul');

   var val3 = util.formatWithOptions(
      { breakLength: 3, colors: true },
      10, 20, 30);

   var val5 = util.formatWithOptions(
      { compact: true }, '%% : %s', 567);

   console.log(val0, '\n', val1, '\n',
      val2, '\n', val3, '\n', val5);
}
// 函数调用
fun();
输出结果
C:\home\node>> node formatWithOptions.js
See object { foo: 21 }
a:b:c
raj:rahul
10 20 30
% : 567

示例 2

//Node.jsutil.formatWithOptions() 方法

// 导入 util 模块
const util = require('util');

console.log("1. ", util.formatWithOptions(
   { colors: true },
   '%%: %s', 'John', 'Cena', -0));

console.log("2. ", util.formatWithOptions(
   {
      showHidden: false, depth: 0,
      colors: true
   }, '%s', 'fun', Object.create(null,
   { [Symbol.toStringTag]: { value: 'function' } })));

console.log("3. ", util.formatWithOptions(
   { colors: true }, '%o',
   class Bar { }, 'fun', 78987965465464));

console.log("4. ", util.formatWithOptions(
   { depth: 0, colors: true }, '%o:%d',
   class Foo { get [Symbol.toStringTag]()
      { return 'fun'; } }, 'fun',
   78987965465464));
输出结果
C:\home\node>> node formatWithOptions.js
1. %: John Cena 0
2. fun [Object: null prototype] [function] {}
3. { [Function: Bar]
[length]: 0,
[prototype]: Bar { [constructor]: [Circular] },
[name]: 'Bar' } fun 78987965465464
4. { [Function: Foo]
   [length]: 0,
   [prototype]:
   Foo [fun] {
      [constructor]: [Circular],
      [Symbol(Symbol.toStringTag)]: [Getter] },
   [name]: 'Foo' }:NaN 78987965465464