← 中文资源

简体中文版本

util.format 拼装命令行输出

用 %s %d %j 占位符组装命令行文本:多余参数以空格追加不会丢失,缺占位符的对象走 inspect 展示,%d 收到非数字只会得到 NaN 而不是抛错。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

cpu load 87%
job sync -> {"files":3,"bytes":512}
retries=NaN
backup done at 02:00
config { retries: 2, tags: [ 'a', 'b' ] }

实现说明

唯一的导入来源是 node:util(Node.js 内建),暴露出 format。

使用要点

  • node:util 是 Node.js 内建模块——随运行时自带,无需安装。

常见问题

需要安装第三方包吗?

不需要——node:util 是 Node.js 内建模块,无需安装。

代码示例

import { format } from 'node:util';

// %s strings, %d numbers, %j JSON, %% a literal percent sign
console.log(format('%s load %d%%', 'cpu', 87));
console.log(format('%s %s -> %j', 'job', 'sync', { files: 3, bytes: 512 }));

// Non-numeric input to %d becomes NaN instead of throwing
console.log(format('retries=%d', 'many'));

// Extra arguments are appended space-separated, never dropped silently
console.log(format('%s done', 'backup', 'at', '02:00'));

// Objects without a placeholder are inspected with the default depth
console.log(format('config', { retries: 2, tags: ['a', 'b'] }));