Deno nuggets: Overwrite a console log line
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to overwrite/update a console log line?
Solution
Imports
No imports are required.
Use write API
The console.log API always inserts a \n at the end. To overwrite a log line on the console, the low-level write() API needs to be used with Deno core’s Deno.stdout resource handle.
The write() API is useful in writing any bytes on the console. The input is bytes & output is the number of bytes that got written:
write(p: Uint8Array): Promise<number>
To overwrite data on the last line of the console, the write() API needs to be called with new data and a \r at the end. Any string data needs to be converted to bytes (using TextEncoder) before calling the write() API.
await Deno.write(new TextEncoder().encode("A\r"));
await Deno.write(new TextEncoder().encode("B\r"));
The following code keeps writing an incrementing number to the same console log line every 50 milliseconds:
let num = 1;
const enc = (s: string) => new TextEncoder().encode(s);
setInterval(async () => await Deno.stdout.write(enc(`${num++}\r`)), 50);
The following code updates a progress bar every 100 millliseconds:
let num = 0;
const max = 20;
const enc = (s: string) => new TextEncoder().encode(s);
const intId = setInterval(async () => {
await Deno.stdout.write(enc("\r|"));
for (let i = 0; i < max; i++) {
i < num
? await Deno.stdout.write(enc("█"))
: await Deno.stdout.write(enc("░"));
}
await Deno.stdout.write(enc("|"));
if (num == max) {
await Deno.stdout.write(enc("\n"));
clearInterval(intId);
} else {
num++;
}
}, 100);