编写CLI:递归函数意外行为

时间:2016-08-12 02:50:35

标签: node.js

当我遇到一些意外行为时,我正在为我的节点程序编写命令行界面。

// Starts command line prompt bot
// @param {Function} callback - callback upon finshing CL inputs
function main(callback) {
    this.args = []; // store CL args
    this.consoleOutputs = ["Enter input1: ", "Enter input2: ", "enter input3: "];
    this.nextInput = function(consoleOutputs, numInputsLeft) {
        if (numInputsLeft == 0) { callback.apply(null, args); } // done, stop recursing and run callback
        // write output to prompt user
        process.stdout.write(consoleOutputs[consoleOutputs.length-numInputsLeft]);
        process.stdin.on('readable', function() {
            var text = process.stdin.read();
            if (text !== null) {
                console.log(numInputsLeft);
                args.push(text);
                // recurse to print next output and wait for next input
                nextInput(consoleOutputs, numInputsLeft-1);
            }
        });
    }

    nextInput(this.consoleOutputs, consoleOutputs.length);
}

我期望numInputsLeft减少:14,13,12等。 相反,numInputs Left被卡在14,14,14等

为什么会发生这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:0)

实际上问题就在于行

nextInput(consoleOutputs, numInputsLeft-1);

这里每次只有3-1 = 2,因为我们没有将结果存储在任何地方。因此每次它都采用相同的值。

我试过这个代码,它对我来说很好。

请尝试这个希望它有所帮助。

function main(callback) {
this.args = []; // store CL args
this.consoleOutputs = ["Enter input1: ", "Enter input2: ", "enter input3: "];
this.numInputsLeft = consoleOutputs.length;

this.nextInput = function(consoleOutputs, numInputsLeft) {

    if (numInputsLeft == 0) {
      console.log("Ends here !!");
      process.stdin.removeAllListeners('readable')
      return callback(null, args);
    }

    console.log(consoleOutputs[consoleOutputs.length-numInputsLeft]);

    process.stdin.on('readable', function() {
        var text = process.stdin.read();
        if (text !== null) {
            args.push(text.toString().trim());
            numInputsLeft--;
            nextInput(consoleOutputs, numInputsLeft);
        }
    });
}

nextInput(this.consoleOutputs, this.numInputsLeft);
}

    main(function (arg1, arg2) {
      // console.log(arg1);
      console.log(arg2);
    });