padStart Aligns Fixed Width Output

Pad service names with padEnd and latency numbers with padStart to fixed widths so multi-row CLI output lines up into readable aligned columns.

JavascriptCli Tooling

Code

javascriptsnippet
17 lines
// padEnd 垫名字、padStart 垫数字到固定宽度:多行输出对齐成列
const rows = [
  { service: 'api', ms: 123.4 },
  { service: 'web', ms: 8.75 },
  { service: 'worker', ms: 4520.1 },
];

for (const { service, ms } of rows) {
  const name = service.padEnd(10, '.');
  const latency = ms.toFixed(1).padStart(8);
  console.log(`${name} ${latency} ms`);
}

// padStart(6, '0'):日志与 ID 的定长前缀
for (const seq of [7, 42, 2026]) {
  console.log('task-' + String(seq).padStart(6, '0'));
}

Output

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

api.......    123.4 ms
web.......      8.8 ms
worker....   4520.1 ms
task-000007
task-000042
task-002026

How it works

Iteration is nested: for (const { service, ms } of rows) frames the pass, for (const seq of [7, 42, 2026]) does the per-item step.

Top-level bindings rows hold the demo state — nothing sits inside a function scope.

Putting it to use

The demo output is labeled (task-); each label names the call that printed it.

Core lines

const latency = ms.toFixed(1).padStart(8);
const name = service.padEnd(10, '.');

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `rows`.