Library for easily reading lines from standard input
curl -o src/libs/readline.ts https://c2coder.github.io/Jaculus-libraries/data/readline/readline.ts
import { stdout } from "stdio";
import { readline } from "./libs/readline.js";
//* řetězce
async function echo() {
stdout.write("Napiš nějaký text a stiskni enter.\n");
const reader = new readline(false); // vytvoří novou instanci třídy readline
while (true) { // opakuje se donekonečna
const line = await reader.read(); // přečte řádek z konzole
stdout.write("Zadal jsi: " + line + "\n"); // vypíše řádek na konzoli
stdout.write(`Druhá možnost výpisu: Zadal jsi: ${line}\n`); // vypíše řádek na konzoli
if (line == "konec") { // pokud je řádek roven "konec"
stdout.write("Ukončuji.\n"); // vypíše text na konzoli
break; // ukončí cyklus
}
}
reader.close(); // ukončí čtení z konzole
}
echo(); // zavolá funkci echo
import { stdout, stdin } from "stdio";
/**
* A class for reading standard input line by line.
*/
export class readline {
private buffer: string = "";
private promise: Promise<string> | null = null;
private resolve: ((value: string) => void) | null = null;
private reject: ((reason: any) => void) | null = null;
private closed: boolean = false;
private echo: boolean;
private onGet(str: string) {
if (this.echo) {
stdout.write(str);
}
if (str == "\n") {
if (this.resolve) {
this.resolve(this.buffer);
}
this.buffer = "";
this.promise = null;
this.resolve = null;
this.reject = null;
return;
}
this.buffer += str;
if (!this.closed) {
stdin.get()
.then((data) => this.onGet(data))
.catch((reason) => {
if (this.reject) {
this.reject(reason);
}
});
}
}
constructor(echo: boolean = false) {
this.echo = echo;
}
public read(): Promise<string> {
if (this.promise != null) {
return Promise.reject("Already reading");
}
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
stdin.get()
.then((data) => this.onGet(data))
.catch((reason) => {
if (this.reject) {
this.reject(reason);
}
});
return this.promise;
}
public close() {
this.closed = true;
if (this.reject) {
this.reject("Stopped");
}
this.buffer = "";
this.promise = null;
this.resolve = null;
this.reject = null;
}
}