从客户端请求中使用Node运行Bash Script

Run Bash Script with Node from client request

本文关键字:Node 运行 Bash Script 客户端 请求      更新时间:2023-09-26

我需要让一个服务器端脚本运行,当用户从浏览器点击一个按钮…

我已经研究了一段时间了,还是想不出来。

我们有什么:

  • Node.js服务器(在本地主机上)在Fedora Red Hat上运行
  • 大多数页面是html + javascript + jQuery

为了更清楚,下面是我们希望发生的事情:

- - ->用户去http://localhost/index . html

->用户选择颜色,按"提交"按钮

->选择的颜色进入bash脚本(在服务器上)。/sendColors [listOfColors]

-> bash脚本的东西。

================

我尝试过的事情

child_process.spawn

我希望我可以在html页面上这样做:

var spawn = require('child_process').spawn;
ls    = spawn(commandLine, [listOfColors]);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});
ls.on('close', function (code) {
  console.log('child process exited with code ' + code);
});

但是这个脚本是服务器端,而不是客户端,所以我不能在html页面上运行它(我相信)。当我尝试运行这个命令时,我得到的错误是require是未定义的。

browserify

我试过安装browserify,但是我们使用的机器没有连接到互联网,不能使用npm install。我已经手动将文件复制到usr/lib和"required"它很好,但后来它说它找不到"through",这是在browserify的index.js中…

getRuntime

try this thing:

        var bash_exit_code = 0;          // global to provide exit code from bash shell invocation
        function bash(command)
        {
          var c;           // a character of the shell's stdout stream
          var retval = "";          // the return value is the stdout of the shell
          var rt = Runtime.getRuntime();        // get current runTime object
          var shell = rt.exec("bash -c '" + command + "'");   // start the shell
          var shellIn = shell.getInputStream();        // this captures the output from the command
          while ((c = shellIn.read()) != -1)        // loop to capture shell's stdout
            {
              retval += String.fromCharCode(c);        // one character at a time
            }
          bash_exit_code = shell.waitFor();        // wait for the shell to finish and get the return code
          shellIn.close();          // close the shell's output stream
          return retval;
        }

说它不知道Runtime是什么

RequireJS

我已经研究过RequireJS,但不明白如何在我的情况下使用它

eval

我也试过eval…但我认为那是针对代数表达式的…没有工作。

ActiveX

even tried activeX:

variable=new ActiveXObject(...

说它不知道ActiveXObject是什么

================

当前我正在尝试的

HttpServer.js:

var http = require('http');
...
var colors = require('./colorsRequest.js').Request;
...
http.get('http://localhost/colorsRequest', function(req, res){
    // run your request.js script
    // when index.html makes the ajax call to www.yoursite.com/request, this runs
    // you can also require your request.js as a module (above) and call on that:
    res.send(colors.getList()); // try res.json() if getList() returns an object or array
    console.log("Got response ");// + res.statusCode);
    });

colorsRequest.js

var RequestClass = function() {
    console.log("HELLO");
}; 
// now expose with module.exports:
exports.Request = RequestClass;

index . html

...
var colorsList = ...
...
$.get('http://localhost/colorsRequest', function(colors) {
            $('#response').html(colorsList); // show the list
    });

我得到

GET http://localhost/colorsRequest 404 (Not Found)

有人有什么想法吗?

这是一个简单的服务器模板(它使用Express,所以你可能需要先安装它:npm install express):

var spawn   = require('child_process').spawn;
var express = require('express');
var app     = express();
app.use(express.static(__dirname));
app.get('/colorsRequest', function(req, res) {
  var command = spawn(__dirname + '/run.sh', [ req.query.color || '' ]);
  var output  = [];
  command.stdout.on('data', function(chunk) {
    output.push(chunk);
  }); 
  command.on('close', function(code) {
    if (code === 0)
      res.send(Buffer.concat(output));
    else
      res.send(500); // when the script fails, generate a Server Error HTTP response
  });
});
app.listen(3000);

你可以给它传递一个颜色,它将运行shellscript run.sh(它假设它位于与服务器JS文件相同的目录中),并将颜色作为参数传递:

curl -i localhost:3000/colorsRequest?color=green
# this runs './run.sh green' on the server
下面是一个HTML模板页面(保存为index.html,将其与服务器代码和shell脚本放在同一目录下,启动服务器,并在浏览器中打开http://localhost:3000):
<!doctype html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  </head>
  <body>
    <select>
      <optgroup label="Pick a color:">
        <option>green</option>
        <option>blue</option>
        <option>yellow</option>
        <option>orange</option>
      </optgroup>
    </select>
    <script>
      $('select').on('change', function() {
        $.get('/colorsRequest', { color : $(this).val() });
      });
    </script>
  </body>
</html>

您的第一种方法(child_process.spawn变体)是正确的。当然你不能把它放在HTML页面中,因为它是在浏览器中执行的,而不是在服务器中,但是你可以很容易地在浏览器中创建一个请求(AJAX或页面加载,取决于你需要什么),触发在服务器中运行这个脚本。

相关文章: