util.format Builds CLI Output Strings

Compose command-line lines with %s %d %j placeholders; extra arguments are appended instead of dropped and objects pass through inspect formatting.

JavascriptCli Tooling

Code

javascriptsnippet
14 lines
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'] }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Peering into the code

The only import source is node:util, a Node.js built-in, exposing format.

Watch out for

  • node:util is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:util` is a Node.js built-in module; nothing to install.