Node.js – util.formatWithOptions() 方法
util.formatWithOptions() 方法与 util.format() 方法的工作方式相同。两者的唯一区别在于,formatWithOptions() 方法采用 inspectOptions 参数,该参数指定要传递给 util.inspect() 方法的选项。
语法
util.formatWithOptions(inspectOptions, format, [args])
参数
参数如下定义
- inspectOptions − 这些选项将用于检查传递给此方法的对象。
- format − 此参数采用传递的输入值的格式类型的输入。
示例 1
创建一个名为 "formatWithOptions.js" 的文件并复制以下代码段。创建文件后,使用命令 "node formatWithOptions.js" 运行此代码。
// Node.js util.formatWithOptions() method
// Importing the util module
const util = require('util');
function fun() {
// Passing different options along the format
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, '
', val1, '
',
val2, '
', val3, '
', val5);
}
// Function call
fun();输出
C:\home
ode>> node formatWithOptions.js See object { foo: 21 } a:b:c raj:rahul 10 20 30 % : 567
示例 2
// Node.js util.formatWithOptions() method
// Importing the util module
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
ode>> 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP