How to format console output with Node.js?

Sometimes, we want to format console output with Node.js.

In this article, we’ll look at how to format console output with Node.js.

How to format console output with Node.js?

To format console output with Node.js, we can use the string padStart and padEnd methods.

For instance, we write

'abc'.padStart(10, "foo");

to prepend the 'abc' string with 'foo' until its length is 10.

So it returns "foofoofabc".

If we skip the 2nd argument, empty space will be prepended.

Also, we can append to a string until it reaches the given length with padEnd.

For instance, we write

'abc'.padEnd(10, "foo");

to call padEnd to append the 'abc' string with 'foo' until its length is 10.

So it returns "abcfoofoof".

If we skip the 2nd argument, empty space will be appended.

Conclusion

To format console output with Node.js, we can use the string padStart and padEnd methods.