saghul/txiki.js

How to get input from the terminal

ahaoboy opened this issue ยท 4 comments

I want to use txiki to run some terminal programs and need to be able to get user input. The simplest demo is as follows, but it seems that txiki does not have a process module, or other interfaces that can get user input?

process.stdin.addListener("data", (s) => {
  console.log("data:", s.toString());
});

The link in this issue is no longer valid. #404

I'm working on some better documentation ๐Ÿ˜…

There is tjs.stdin which has this API: https://bettercallsaghul.com/txiki.js/api/interfaces/global.tjs.StdioInputStream.html

So you can do:

const buf = new Uint8Array(4096);
const nread = await tjs.stdin.read(buf);
console.log(new TextDecoder().decode(buf.subarray(0, nread)));

The API is pull-based, rather than event based.

Thanks for the quick reply, this does work, but it is not compatible with the nodejs API. If I want to implement a general library, I have to do a separate process for txiki.

That is correct and by design. txiki.js does not aim to implement the Nodejs API.

A simple polyfill

const process = {
  stdin: {
    async addListener(name, cb) {
      while (true) {
        const buf = new Uint8Array(4096);
        const nread = await tjs.stdin.read(buf);
        cb(new TextDecoder().decode(buf.subarray(0, nread)))
      }
    }
  }
}


process.stdin.addListener("data", (s) => {
  console.log("data:", s.toString().trim());
});