Run Bash Script with Node from client request

前端 未结 2 1812
青春惊慌失措
青春惊慌失措 2021-02-02 02:22

I need to make a server-side script run when a user from the browser clicks a button...

I\'ve been researching for a while, and can\'t figure it out.

What we hav

相关标签:
2条回答
  • 2021-02-02 02:31

    Here's a simple boilerplate for the server (which uses Express, so you might need to install that first: 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);
    

    You can pass it a color, and it will run the shellscript run.sh (of which it assumes is located in the same directory as the server JS file) with the color passed as argument:

    curl -i localhost:3000/colorsRequest?color=green
    # this runs './run.sh green' on the server
    

    Here's a boilerplate HTML page (save it as index.html, put it in the same directory as the server code and the shell script, start the server, and open http://localhost:3000 in your browser):

    <!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>
    
    0 讨论(0)
  • 2021-02-02 02:37

    You are on the right way with your first approach, the child_process.spawn variant. Ofcourse you can't put this in the HTML page, as it is then executed in the browser, not in the server, but you can easily create a request in the browser (AJAX or page load, depending on what you need), that triggers running this script in the server.

    0 讨论(0)
提交回复
热议问题