Amit DhamuSoftware Engineer

Overwrite console output in Node

1 minute read 00000 views

We can use process.stdout to overwrite console output in Node.

As an example, if we wanted to track the progress of a long running loop, we could use something like the code below.

timer simulates a long running process. This could be a time-consuming request.

const items = Array.from({ length: 100 }, (_, i) => i)

const timer = ms => new Promise(res => setTimeout(res, ms))

async function main() {
  for (const [i, item] of items.entries()) {
    await timer(100)

    process.stdout.write(`${i + 1}/${items.length}`)