节点奇怪的用户输入异步行为

时间:2018-12-16 20:24:00

标签: javascript node.js promise command-line-interface

我刚刚习惯于Node编程,但是遇到了这个执行问题,对此我感到有些困惑。

我正在尝试测试写路径是否已经存在,然后是否要求用户输入。

function testPath(fileName) {
  fs.exists(path.resolve('.', fileName), function(exists) {
  //the filepath already exists, ask for user confirmation
  if(exists) {
    process.stdin.on('keypress', function (str, key) {
    //print result of keypress to console
    console.log("str: ", str, " key: ", key);

    if ((str.toLowerCase() == "n") || (~["y", "n"].indexOf(str.toLowerCase()))) {
      return false;
    }
    else {
      return true;
    }
  });
  }
  else {
  //the filepath does not already exist - return true
  return true;
}
console.log("Filename in the target directory already exists, would you like to overwrite? (y/n)");
});
}

此功能作为一个整体将通过对其上调用的promise来解决(或不解决)。

发给用户并等待按键的消息似乎以正确的方式起作用,但是它会陷入循环,即使在有效的按键下也永远不会返回,有人知道为什么吗?

1 个答案:

答案 0 :(得分:2)

如果要将其用作承诺,则需要返回承诺:

function testPath(fileName) {
    return new Promise((resolve, reject) => {
        fs.exists(path.resolve('.', fileName), function(exists) {
        //the filepath already exists, ask for user confirmation
        if(exists) {
            process.stdin.on('keypress', function (str, key) {
            //print result of keypress to console
            console.log("str: ", str, " key: ", key);

            if ((str.toLowerCase() == "n") || (~["y", "n"].indexOf(str.toLowerCase()))) {
            return reject();
            }
            else {
            return resolve();
            }
        });
        }
        else {
        //the filepath does not already exist - return true
        return resolve();
        }
        console.log("Filename in the target directory already exists, would you like to overwrite? (y/n)");
        });
        }
    })