NodeJS:无法同步执行shell脚本

时间:2017-03-13 15:41:44

标签: ajax node.js shell

我正在尝试执行shell命令并将输出返回到网页

  app.post("/api/procText", function (request, response) {
      var input = request.body.inString;
      console.log(request.body)
      var exec = require('child_process').execSync;
      var cmd = 'scripts/myScript -s' + '\'' + input + '\'';
      var script_output = ''
      exec(cmd, {
          env: {
              'resources': '/dasd/okok/data'
          }
      }, function (error, stdout, stderr) {
          console.log("Inside exec " + stdout)
          script_output = stdout
      });
      console.log("Outside " + script_output);
      response.send("Sending " + script_output);
  });

但是,script_output始终为空,我也看不到控制台上的内部消息

我做错了什么?

另外,这里是相应的html

<body>
    <div class="container">
        <h1>Welcome.</h1>
        <div id="sampleInput" class="input-group-lg center-block helloInput">
            <p class="lead">Input Text?</p>
            <input id="sample_text" type="text" class="form-control"
                placeholder="inString" aria-describedby="sizing-addon1" value="" />
        </div>
        <p id="response" class="lead text-center"></p>


    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script
        src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script>
        //Submit data when enter key is pressed
        $('#sample_text').keydown(function(e) {
            var inString = $('#sample_text').val();
            if (e.which == 13 && inString.length > 0) { //catch Enter key
                //POST request to API to create a new visitor entry in the database
                $.ajax({
                    method : "POST",
                    url : "./api/procText",
                    contentType : "application/json",
                    data : JSON.stringify({
                        inString : inString
                    })
                }).done(function(data) {
                    alert(data);
                    $('#response').html(data);
                    $('#sampleInput').hide();

                });
            }
        });
    </script>
</body>

1 个答案:

答案 0 :(得分:0)

我明白了。我所要做的就是使用回调返回stdout

script_output=exec(cmd, {env: {'NLTK_DATA': process.cwd()+"/scripts/nltk_data"}}, function(error, stdout, stderr) {
    console.log("Inside exec "+stdout);
    return stdout;
});
  console.log("Sending "+script_output);
response.send(script_output);