代码之家  ›  专栏  ›  技术社区  ›  LePioo

nodejs响应shell提示

  •  1
  • LePioo  · 技术社区  · 6 年前

    我从nodejs应用程序启动了一个shell脚本。
    在某一点上,shell脚本要求用户输入(Y/N确认)。
    节点应用程序在raspberrypi上运行,通过物理按钮(无键盘)进行确认,因此“提示应答”必须通过代码进行。
    我试过:

    childProcess.stdin.write("y\n");
    childProcess.stdin.end();
    

    但什么也没发生。
    为了清楚起见,我已经在控制台上手动测试了输入“y”并且它可以工作,脚本继续它的过程。

    这是我简化的代码:

    节点应用程序:

    var Gpio = require('pigpio').Gpio;
    class Main {
      constructor() {
        this.prompt = false;
        const button = new Gpio(17, {
          mode: Gpio.INPUT,
          pullUpDown: Gpio.PUD_DOWN,
          edge: Gpio.EITHER_EDGE
        });
        button.on('interrupt', (level) => {
          if (level == 1) {
            this.onButtonPress();
          } else if (level == 0) {
            this.onButtonRelease();
          }
        });
        this.childProcess = require('child_process').spawn('sudo', ['miLazyCracker']);
        this.childProcess.stdout.on('data', (dataBuffer) => {
          var data = dataBuffer.toString();
          console.log(data);
          if (data.includes("Do you want clone the card?")) {
            this.prompt = true;
          }
        });
      }
      onButtonPress() {
    
      }
      onButtonRelease() {
        if (this.prompt) {
          this.childProcess.stdin.write("y\n");
          this.childProcess.stdin.end();
          console.log("sent prompt confirmation");
        }
      }
    }
    new Main();
    module.exports = Main;
    

    shell脚本: https://github.com/nfc-tools/miLazyCracker/blob/master/miLazyCracker.sh

    下面是简单化的控制台输出:

    [Useless start of the script]
    
    Do you want clone the card? Place card on reader now and press Y [y/n]
    sent prompt confirmation
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   LePioo    6 年前

    问题出在sh脚本本身,它显然使用了一种无法从脚本中获得答案的提示方法,我使用常规读取方法对其进行了修改,现在它开始工作了。 谢谢你的评论