Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get input from the terminal #603

Closed
ahaoboy opened this issue Jul 15, 2024 · 4 comments
Closed

How to get input from the terminal #603

ahaoboy opened this issue Jul 15, 2024 · 4 comments

Comments

@ahaoboy
Copy link
Contributor

ahaoboy commented Jul 15, 2024

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

@saghul
Copy link
Owner

saghul commented Jul 15, 2024

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.

@ahaoboy
Copy link
Contributor Author

ahaoboy commented Jul 15, 2024

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.

@saghul
Copy link
Owner

saghul commented Jul 15, 2024

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

@ahaoboy
Copy link
Contributor Author

ahaoboy commented Jul 15, 2024

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());
});


@saghul saghul closed this as completed Jul 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants