首页 > 解决方案 > How to read only a single line from command line in Node.js, similar to Python's `input` or C++'s `std::getline`?

问题描述

In Node, there does not seem to be a straight-forward way to easily get a single line from the commandline.

Solutions I have found so far:

  1. readline module's on('line', callback) [*]
  2. readline's question(q, callback) [*]
  3. process.stdin.pipe(require('split')()).on('data', callback) [*]
  4. fs.readFileSync(0).toString [*]

But all of the above are not nearly as straight forward as python's input or C++'s std::getline. (Also, I could not get option (4) to work on Windows.)

The readline approach is probably the best, but the fact that it requires the use of callbacks is frustrating.

标签: javascriptnode.jsinputcommand-line

解决方案


Wrapping the dedicated readline module's function(s) in promises is probably still the best approach. Here we emulate Python's input and C++'s getline functionality.

NOTE that node event's don't only have an on function, but also a once function.

// input.js

const readline = require('readline');

const cmd = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});


/**
 * Emulate Python's `input` function.
 */
export async function input(prompt) {
  return new Promise(r => cmd.question(prompt, r));
}

/**
 * Emulate C++'s `getline` function.
 */
export async function getline() {
  return new Promise(r => cmd.once('line', r));
}
// main.js

async function main() {
  const x = await input('What is x?');
  console.log('x is', x);

  console.log('What is y?');
  const y = await getline();
  console.log('y is', y);
}

main();

推荐阅读