Deno nuggets: Write raw data on console

Mayank C
Tech Tonic

--

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 write raw data to console i.e. without new line that comes default with console.log?

Instead of writing like this,

write like this:

Solution

Imports

No imports are required.

Write raw data

To write raw data to the console, the low-level Deno.stdout.write API can be used instead of high-level console.log API. The difference is that the low-level write API writes the exact data to the console without performing any kind of formatting.

If console.log is used, it’ll add a newline for every API call:

setInterval(() => console.log("."), 100);//--$ deno run app.ts 
.
.
.
.
^C

The only issue with low-level write API is that, it expects raw bytes instead of strings. The string data can be converted to raw data using TextEncoder’s encode API. It’ll be useful to write a small utility function to do that.

The above code with console.log can be rewritten using Deno.stdout.write like this:

const enc = (s: string) => new TextEncoder().encode(s);
setInterval(() => Deno.stdout.write(enc(".")), 100);

A run of the above code produces the desired results:

$ deno run app.ts 
.....................................^C

--

--