pomdtr
pomdtr9mo ago

How to read all text from stdin.

It uses to be simple with the Deta.readAll function. Now it is deprecated, link to https://deno.land/std/streams/read_all.ts?s=readAll (which is also deprecated). The deprecation message says: Use ReadableStream and toArrayBuffer instead. A specific example would be better. Basically, I want
const text = await Deno.readTextFile("/dev/stdin");
const text = await Deno.readTextFile("/dev/stdin");
but working on windows
7 Replies
pomdtr
pomdtr9mo ago
Ok I found it. Here it is for future reference
import { toArrayBuffer } from "https://deno.land/std@0.203.0/streams/mod.ts";

const input = new TextDecoder().decode(await toArrayBuffer(Deno.stdin.readable))

console.log(input);
import { toArrayBuffer } from "https://deno.land/std@0.203.0/streams/mod.ts";

const input = new TextDecoder().decode(await toArrayBuffer(Deno.stdin.readable))

console.log(input);
Deno AI Helper
Deno AI Helper9mo ago
To read all text from stdin in Deno, you can use the Deno.stdin variable which provides a ReadableStream interface. Here is an example from the documentation:
const decoder = new TextDecoder();
for await (const chunk of Deno.stdin.readable) {
const text = decoder.decode(chunk);
// do something with the text
}
const decoder = new TextDecoder();
for await (const chunk of Deno.stdin.readable) {
const text = decoder.decode(chunk);
// do something with the text
}
In this example, Deno.stdin.readable is a ReadableStream that you can asynchronously iterate over to get chunks of data from stdin. Each chunk is a Uint8Array that you can decode into a string using TextDecoder. Please note that this code will read from stdin until it encounters an EOF (End of File) marker, which signals that there is no more data to read. In a terminal, you can usually send an EOF marker by pressing Ctrl+D (on Unix-like systems) or Ctrl+Z (on Windows). This method should work across different platforms including Windows. However, please note that the behavior might be slightly different depending on the terminal or command line interface you are using.
ioB
ioB9mo ago
Since you're already importing from the std, might as well use toText instead!
import { toText } from "https://deno.land/std@0.203.0/streams/mod.ts";

const input = await toText(Deno.stdin.readable)

console.log(input);
import { toText } from "https://deno.land/std@0.203.0/streams/mod.ts";

const input = await toText(Deno.stdin.readable)

console.log(input);
pomdtr
pomdtr9mo ago
thanks! toJson is also quite useful
ioB
ioB9mo ago
👍
Esente
Esente9mo ago
const input = await new Response(Deno.stdin.readable).json();
const input = await new Response(Deno.stdin.readable).json();
pomdtr
pomdtr9mo ago
wow this looks weird