tooling icon indicating copy to clipboard operation
tooling copied to clipboard

Add web APIs for `alert`, `confirm` and `prompt` to Node.js

Open iansu opened this issue 2 years ago • 2 comments

Deno supports the alert, confirm and prompt web APIs to read input from the user in a terminal context. I think this would be great to have in Node.js as well. Deno documentation is here: https://examples.deno.land/prompts

You can achieve the same thing in Node with readline but it's not as nice of an API. For example, here's how you prompt the user for input using readline from the Node docs (https://nodejs.org/api/readline.html#readline):

const readline = require('node:readline');
const { stdin: input, stdout: output } = require('node:process');

const rl = readline.createInterface({ input, output });

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});

And here's how you would do the same thing with prompt:

const answer = prompt('What do you think of Node.js?');

console.log(`Thank you for your valuable feedback: ${answer}`);

I think these new APIs would be very useful for tool authors and would also bring more web APIs to Node.js.

One possible difficulty implementing these APIs is that they seem to be synchronous in Deno and readline does not work synchronously. I've created a basic POC of these functions using readline (and await) as a starting point here: https://github.com/iansu/node-prompts

iansu avatar Feb 20 '23 23:02 iansu

The functionality seems awesome; I would hope node wouldn't add them as globals with those names, though, since it will likely break (or at best, complicate) environment detection code.

ljharb avatar Feb 20 '23 23:02 ljharb

If we were to add these in a module do you think it would still be worthwhile to make the API compatible with the browser implementations? This could help decide if these functions should be synchronous or asynchronous as well.

iansu avatar Mar 08 '23 00:03 iansu