等待node.js中的用户输入

Jpa*_*ish 2 javascript user-input synchronous wait node.js

我只是想提一下,我尝试了一些来自博客的技术来获取用户输入但是示例总是在一个只询问用户输入的程序的上下文中......并且它们总能工作但是从来没有任何节点问题. js继续到下一行代码,因为没有.

我必须得到用户输入,然后验证输入是否有效,所以我创建了这个构造:

while ( designAppealTest(subject) == false ) {
            subject[DESIGN_APPEAL] = ei.errorInput('designAppeal for the subject', iteration, subject[DESIGN_APPEAL])
        }
Run Code Online (Sandbox Code Playgroud)

它调用的函数是:

module.exports.errorInput =  function (fieldName, iteration, originalValue) {
    originalValue = originalValue || 'false'
    console.log('\n\n' + fieldName + ' for the subject' + ' contains an invalid value in for #' + i)

    if (originalValue !== false)
        console.log('original value of field = ' + originalValue)

    console.log('\nPlease enter a new value for it:\n')

    process.stdin.on('data', function (text) {
        console.log('received data:', text);
        return text;
    });

}
Run Code Online (Sandbox Code Playgroud)

除了在用户有机会输入值之前它继续通过while循环之外,这是有效的.所以我看到的是提示用户每秒输入40,000次的值.在继续循环之前,如何使node.js等到输入值?构造本身是错误的还是因为我没有停止异步?

CFrei:

好的,我也给check()自己添加了一个回调:

checkedSubject = check(subject, function(v) {
            return v;
        });

        console.log('checkedSubject = ' + checkedSubject)

        function check(listing, callback) {
            if (designAppealTest(subject) == false ) {
                ei.errorInput('designAppeal', iteration, listing[DESIGN_APPEAL], function(v) {
                    listing[DESIGN_APPEAL] = v;
                    check(listing)
                    });
            } else {
                callback(listing);
            }
        }
Run Code Online (Sandbox Code Playgroud)

我仍然遇到同样的问题 - 它会要求输入但是立即执行后面的所有操作.

Kar*_*ler 5

由于这个问题有点旧,但我猜它仍然得到了谷歌的大量流量:你应该看看nodejs readline

const readline = require('readline');

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

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();
});
Run Code Online (Sandbox Code Playgroud)