Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/esm/workerd/cli.js>lockStdin

A JavaScript extension package for building strong and modern applications.
Latest
function lockStdin
import { lockStdin } from "https://deno.land/x/ayonli_jsext@v0.9.72/esm/workerd/cli.js";

Requests the standard input to be used only by the given task until it is completed.

This function sets the stdin in raw mode, and excludes other parts of the program from reading from it at the same time . This is important so that our program won't be affected by other tasks, especially in a REPL environment.

Examples

Example 1

// A simple program that reads a line of text from user input.
import process from "node:process";
import bytes, { equals } from "@ayonli/jsext/bytes";
import { chars } from "@ayonli/jsext/string";
import {
    ControlKeys,
    ControlSequences,
    lockStdin,
    readStdin,
    writeStdout,
    isTypingInput,
    moveLeftBy,
} from "@ayonli/jsext/cli";

const input = await lockStdin(async () => {
    await writeStdout(bytes("Type something: "));

    const buf: string[] = []

    while (true) {
        const input = await readStdin();

        if (equals(input, ControlKeys.CTRL_C) || equals(input, ControlKeys.ESC)) {
            console.error("\nUser cancelled");
            process.exit(1);
        } else if (equals(input, ControlKeys.CR) || equals(input, ControlKeys.LF)) {
            await writeStdout(ControlKeys.LF);
            break;
        } else if (equals(input, ControlKeys.BS) || equals(input, ControlKeys.DEL)) {
            if (buf.length > 0) {
                const char = buf.pop()!;
                await moveLeftBy(char);
                await writeStdout(ControlSequences.CLR_RIGHT);
            }
        } else if (isTypingInput(input)) {
            buf.push(...chars(String(input)));
            await writeStdout(input);
        }
    }

    return buf.join("")
});

console.log(`You typed: ${input}`);