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.
Code
// 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-002026How 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.