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


  • format <string> 一个类似 printf 的格式字符串。

util.format() 方法返回一个格式化的字符串,使用第一个参数作为类似 printf 的格式字符串,该字符串可以包含零个或多个格式说明符。每个说明符会被对应参数转换后的值替换。支持的说明符有:

🌐 The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. Each specifier is replaced with the converted value from the corresponding argument. Supported specifiers are:

  • %s:String 将用于转换除 BigInt、Object 和 -0 之外的所有值。BigInt 值将用 n 表示,而既没有用户定义的 toString 函数也没有 Symbol.toPrimitive 函数的对象,将使用带有选项 { depth: 0, colors: false, compact: 3 } 的 util.inspect() 进行检查。
  • %d:Number 将用于转换除 BigInt 和 Symbol 之外的所有值。
  • %i:parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。
  • %f:parseFloat(value) 用于除 Symbol 之外的所有值。
  • %j:JSON。如果参数包含循环引用,则替换为字符串 '[Circular]'。
  • %o:Object。使用通用 JavaScript 对象格式的对象的字符串表示。类似于 util.inspect(),但带有选项 { showHidden: true, showProxy: true }。这将显示完整的对象,包括不可枚举的属性和代理。
  • %O:Object。使用通用 JavaScript 对象格式表示对象的字符串表示形式。类似于不带选项的 util.inspect()。这将显示完整的对象,但不包括不可枚举属性和代理。
  • %c:CSS。此指定符会被忽略,并且会跳过传入的任何 CSS。
  • %%:单个百分号('%')。这不会消耗参数。
  • 返回:<string> 格式化字符串

如果说明符没有相应的参数,则不会替换它:

🌐 If a specifier does not have a corresponding argument, it is not replaced:

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

如果值不属于格式字符串的一部分,并且其类型不是 string,则会使用 util.inspect() 进行格式化。

🌐 Values that are not part of the format string are formatted using util.inspect() if their type is not string.

如果传递给 util.format() 方法的参数比占位符的数量多,多余的参数会被连接到返回的字符串中,并用空格分隔:

🌐 If there are more arguments passed to the util.format() method than the number of specifiers, the extra arguments are concatenated to the returned string, separated by spaces:

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

如果第一个参数不包含有效的格式说明符,util.format() 会返回一个字符串,该字符串是所有参数通过空格连接起来的结果:

🌐 If the first argument does not contain a valid format specifier, util.format() returns a string that is the concatenation of all arguments separated by spaces:

util.format(1, 2, 3);
// Returns: '1 2 3' 

如果只向 util.format() 传递一个参数,该参数将原样返回,不进行任何格式化:

🌐 If only one argument is passed to util.format(), it is returned as it is without any formatting:

util.format('%% %s');
// Returns: '%% %s' 

util.format() 是一个同步方法,旨在作为调试工具使用。一些输入值可能会带来显著的性能开销,从而阻塞事件循环。请谨慎使用此函数,切勿在高频率执行的代码路径中使用。