インタラクティブにコンソールから値を読み取る


155

コンソール拡張を備えたシンプルなサーバーhttpサーバーを作成することを考えました。コマンドラインデータから読み取るスニペットを見つけました。

  var i = rl.createInterface(process.stdin, process.stdout, null);
  i.question('Write your name: ', function(answer) {
    console.log('Nice to meet you> ' + answer);
    i.close();
    process.stdin.destroy();

  });

繰り返し質問をするのによく、私は単純にwhile(done) { }ループを使用できませんか?また、サーバーが質問時に出力を受け取った場合も、行を台無しにします。


5
私はrlあなたによってreadlineを意味すると思いますか?
jpaugh 2017

この回答で使用されているような非ブロッキングインターフェイスを使用して、while(done)ループを実行できます。
Keyvan

回答:


182

「while(done)」ループを実行することはできません。これは、入力のブロックが必要になるため、node.jsは実行したくないためです。

代わりに、何かが入力されるたびに呼び出されるコールバックを設定します。

var stdin = process.openStdin();

stdin.addListener("data", function(d) {
    // note:  d is an object, and when converted to a string it will
    // end with a linefeed.  so we (rather crudely) account for that  
    // with toString() and then trim() 
    console.log("you entered: [" + 
        d.toString().trim() + "]");
  });

2
この作品のおかげで、「終了」リスナーはいくつかの終了操作を呼び出して「さようなら」と言うことができますか?
Risto Novik

例から「終了」リスナーを削除しましたが、正直に言ってどこが本当に役立つかわかりません。
ロブ・

2
d.toString()。trim()への文字列出力を簡略化できます
MKN Webソリューション

6
この回答の日付は2011年であり、それ以降、多くの変更がありました。特に、答えの最初の部分であるwhileループ実行できません...もう保持されません。はい、async-awaitパターンのおかげで、whileループが発生してもブロックされません。他の答えはそれを反映しています。最近これを読んでいる人には、他の回答も参考にしてください。
Wiktor Zychla

1
@WiktorZychlaをフォローするために、機能中の関数process.openStdinは2011年頃に非推奨になり、それに関するドキュメントは見つかりません。
calder.ty

111

この目的で別のAPIを使用しました。

var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('guess> ');
rl.prompt();
rl.on('line', function(line) {
    if (line === "right") rl.close();
    rl.prompt();
}).on('close',function(){
    process.exit(0);
});

これにより、答えがになるまでループ内でプロンプトを出すことができますright。また、素敵な小さなコンソールも提供します。詳細は、http://nodejs.org/api/readline.html#readline_example_tiny_cliで確認できます。


11
これは素晴らしい答えです。明らかではないかもしれませんが(大きなプラスです)、readlineは外部依存関係ではないということです。これはnode.jsの一部です。
jlh 2017年

51

Readline APIは12 '以降かなり変更されています。ドキュメントは、標準ストリームからユーザー入力をキャプチャするための便利な例を示しています。

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  console.log('Thank you for your valuable feedback:', answer);
  rl.close();
});

詳細はこちら。


5
これは単なる基本的な例です。どのように相互作用しますか?質疑応答?複数の選択肢など?いったん閉じたrlを再度開く方法。もしopen rlを使用してユーザーと対話する方法がいくつかのロジックを含めてできない場合
Pawel Cioch

28

async-awaitnode> = 7.xが使用されていると仮定すると、これは現代的な答えに値すると思います。

答えはまだ使用してReadLine::questionいますが、それをwhile (done) {}可能にするためにラップしています。これは、OPが明示的に要求するものです。

var cl = readln.createInterface( process.stdin, process.stdout );
var question = function(q) {
    return new Promise( (res, rej) => {
        cl.question( q, answer => {
            res(answer);
        })
    });
};

そして使用例

(async function main() {
    var answer;
    while ( answer != 'yes' ) {
        answer = await question('Are you sure? ');
    }
    console.log( 'finally you are sure!');
})();

次の会話につながります

Are you sure? no
Are you sure? no
Are you sure? yes
finally you are sure!

これがまさに私が探していた答えです。一番だと思います。
William Chou

綺麗な。大きなスクリプトには非同期待機が必要です。これはまさに私が必要としたものです。
Abhay Shiro

25

readline-syncを使用してください。これにより、コールバックの地獄なしで同期コンソールを操作できます。パスワードでも機能します:

var favFood = read.question('What is your favorite food? ', {
  hideEchoBack: true // The typed text on screen is hidden by `*` (default). 
});


5
これには追加の依存関係が必要なので、他の解決策を選びます。
Risto Novik 2017年

SOで実行されない "Uncaught ReferenceError:read is not defined"
awwsmm

12

@robの回答はほとんどの場合に機能しますが、長い入力では期待どおりに機能しない可能性があります。

代わりにそれを使用する必要があります。

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', d => {
  content += d.toString();
});

stdin.addListener('end', () => {
  console.info(`Input: ${content}`);
});

このソリューションが機能する理由の説明:

addListener('data') バッファのように機能し、コールバックは、それがいっぱいになったとき、および/またはその入力の終わりに呼び出されます。

長い入力はどうですか?単一の'data'コールバックでは十分ではないため、入力が2つ以上の部分に分割されます。それはしばしば不便です。

addListener('end')stdinリーダーが入力の読み取りを完了すると通知します。以前のデータを保存していたので、それをすべて読み取って一緒に処理することができます。


3
上記のコードを使用して入力を挿入し、「Enter」キーを押すと、コンソールはさらに入力を要求し続けます。どのようにそれを終了する必要がありますか?
Matan Tubul 2018年

5

Inquirerを使用することをお勧めします。これは、一般的な対話型コマンドラインユーザーインターフェイスのコレクションを提供するためです。

const inquirer = require('inquirer');

const questions = [{
  type: 'input',
  name: 'name',
  message: "What's your name?",
}];

const answers = await inquirer.prompt(questions);
console.log(answers);

5

次に例を示します。

const stdin = process.openStdin()

process.stdout.write('Enter name: ')

stdin.addListener('data', text => {
  const name = text.toString().trim()
  console.log('Your name is: ' + name)

  stdin.pause() // stop reading
})

出力:

Enter name: bob
Your name is: bob

いい答えの兄弟!! シンプルでクリア。
MD.JULHAS HOSSAIN

3

これは非常に複雑です。より簡単なバージョン:

var rl = require('readline');
rl.createInterface... etc

使用することになります

var rl = require('readline-sync');

それを使用すると待機します

rl.question('string');

その後、繰り返しが簡単です。例えば:

var rl = require('readline-sync');
for(let i=0;i<10;i++) {
    var ans = rl.question('What\'s your favourite food?');
    console.log('I like '+ans+' too!');
}

2

一般的な使用例は、おそらくアプリが汎用プロンプトを表示し、それをswitchステートメントで処理することです。

コールバックで自分自身を呼び出すヘルパー関数を使用して、whileループと同等の動作を得ることができます。

const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);

function promptInput (prompt, handler)
{
    rl.question(prompt, input =>
    {
        if (handler(input) !== false)
        {
            promptInput(prompt, handler);
        }
        else
        {
            rl.close();
        }
    });
}

promptInput('app> ', input =>
{
    switch (input)
    {
        case 'my command':
            // handle this command
            break;
        case 'exit':
            console.log('Bye!');
            return false;
    }
});

'app> 'アプリがこのループの外側ですでに何かを画面に出力している場合は、代わりに空の文字列を渡すことができます。


2

これに対する私のアプローチは、非同期ジェネレータを使用することです。

一連の質問があると仮定します。

 const questions = [
        "How are you today ?",
        "What are you working on ?",
        "What do you think of async generators ?",
    ]

awaitキーワードを使用するには、プログラムを非同期IIFEにラップする必要があります。

(async () => {

    questions[Symbol.asyncIterator] = async function * () {
        const stdin = process.openStdin()

        for (const q of this) {
            // The promise won't be solved until you type something
            const res = await new Promise((resolve, reject) => {
                console.log(q)

                stdin.addListener('data', data => {
                    resolve(data.toString())
                    reject('err')
                });
            })

            yield [q, res];
        }

    };

    for await (const res of questions) {
        console.log(res)
    }

    process.exit(0)
})();

推測される結果:

How are you today ?
good
[ 'How are you today ?', 'good\n' ]
What are you working on ?
:)
[ 'What are you working on ?', ':)\n' ]
What do you think about async generators ?
awesome
[ 'What do you think about async generators ?', 'awesome\n' ]

質問と回答をまとめて取得したい場合は、簡単な変更でこれを実現できます。

const questionsAndAnswers = [];

    for await (const res of questions) {
        // console.log(res)
        questionsAndAnswers.push(res)
    }

    console.log(questionsAndAnswers)

   /*
     [ [ 'How are you today ?', 'good\n' ],
     [ 'What are you working on ?', ':)\n' ],
     [ 'What do you think about async generators ?', 'awesome\n' ] ]
   */

2

コマンドラインから入力を受け取る「tic-tac-toe」ゲームをNodeで作成する必要があり、トリックを実行するこの基本的な非同期/待機ブロックのコードを記述しました。

const readline = require('readline')

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

async function getAnswer (prompt) {
  const answer = await new Promise((resolve, reject) =>{
    rl.question(`${prompt}\n`, (answer) => {
      resolve(answer)
    });
  })
  return answer
}

let done = false
const playGame = async () => {
  let i = 1
  let prompt = `Question #${i}, enter "q" to quit`
  while (!done) {
    i += 1
    const answer = await getAnswer(prompt)
    console.log(`${answer}`)
    prompt = processAnswer(answer, i)
  }
  rl.close()
}

const processAnswer = (answer, i) => {
  // this will be set depending on the answer
  let prompt = `Question #${i}, enter "q" to quit`
  // if answer === 'q', then quit
  if (answer === 'q') {
    console.log('User entered q to quit')
    done = true
    return
  }
  // parse answer

  // if answer is invalid, return new prompt to reenter

  // if answer is valid, process next move

  // create next prompt
  return prompt
}

playGame()

1

ブロックされたreadlineのブロックされていない動作

readline標準モジュールが「ブロックされていない」動作をしているため、このコードが実行されないことがわかったので、コンソールから回答する3つの質問があると想像してください。各rl.questionは独立したスレッドなので、このコードは実行されません。

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

function askaquestion(question) {
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(question[0], function(answer) {
    console.log(answer);
    question[1] = answer;
    rl.close();
  });
};

var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i]);
}

console.log('Results:',questionaire );

実行中の出力:

node test.js
Third Question: Results: [ [ 'First Question: ', '' ],
  [ 'Second Question: ', '' ],
  [ 'Third Question: ', '' ] ]        <--- the last question remain unoverwritten and then the final line of the program is shown as the threads were running waiting for answers (see below)
aaa        <--- I responded with a single 'a' that was sweeped by 3 running threads
a        <--- Response of one thread

a        <--- Response of another thread

a        <--- Response of another thread (there is no order on threads exit)

提案されたソリューションは、イベントエミッターを使用して非ブロック化スレッドの終了を通知し、ループロジックとプログラムの終了をそのリスナー関数に含めます。

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

// Introduce EventEmitter object
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {};

const myEmitter = new MyEmitter();
myEmitter.on('continue', () => {
  console.log('continue...');
  i++; if (i< questionaire.length) askaquestion(questionaire[i],myEmitter);    // add here relevant loop logic
           else console.log('end of loop!\nResults:',questionaire );
});
//

function askaquestion(p_question,p_my_Emitter) { // add a parameter to include my_Emitter
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(p_question[0], function(answer) {
    console.log(answer);
    p_question[1] = answer;
    rl.close();
    myEmitter.emit('continue');    // Emit 'continue' event after the question was responded (detect end of unblocking thread)
  });
};

/*var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i],myEmitter);
}*/

var i=0;
askaquestion(questionaire[0],myEmitter);        // entry point to the blocking loop


// console.log('Results:',questionaire )    <- moved to the truly end of the program

実行中の出力:

node test2.js
First Question: 1
1
continue...
Second Question: 2
2
continue...
Third Question: 3
3
continue...
done!
Results: [ [ 'First Question: ', '1' ],
  [ 'Second Question: ', '2' ],
  [ 'Third Question: ', '3' ] ]

0

私はディレクトリを読み取るための小さなスクリプトを作成し、コンソール名の新しいファイル(例: 'name.txt')とテキストをファイルに書き込みました。

const readline = require('readline');
const fs = require('fs');

const pathFile = fs.readdirSync('.');

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

file.question('Insert name of your file? ', (f) => {
  console.log('File is: ',f.toString().trim());
  try{
    file.question('Insert text of your file? ', (d) => {
      console.log('Text is: ',d.toString().trim());
      try {
        if(f != ''){
          if (fs.existsSync(f)) {
            //file exists
            console.log('file exist');
            return file.close();
          }else{
            //save file
            fs.writeFile(f, d, (err) => {
                if (err) throw err;
                console.log('The file has been saved!');
                file.close();
            });
          }
        }else{
          //file empty 
          console.log('Not file is created!');
          console.log(pathFile);
          file.close();
        }
      } catch(err) {
        console.error(err);
        file.close();
      }
    });
  }catch(err){
    console.log(err);
    file.close();
  }
});

0

最も簡単な方法は、readline-syncを使用することです

入出力を1つずつ処理します。

npm i readline-sync

例えば:

var firstPrompt = readlineSync.question('Are you sure want to initialize new db? This will drop whole database and create new one, Enter: (yes/no) ');

if (firstPrompt === 'yes') {
    console.log('--firstPrompt--', firstPrompt)
    startProcess()
} else if (firstPrompt === 'no') {
    var secondPrompt = readlineSync.question('Do you want to modify migration?, Enter: (yes/no) ');
    console.log('secondPrompt ', secondPrompt)
    startAnother()
} else {
    console.log('Invalid Input')
    process.exit(0)
}

あなたは本当にあなたのrequire声明を含めるべきです。省略しない理由はありません。
solidstatejake
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.