Run Bash Script with Node from client request

前端 未结 2 1861
青春惊慌失措
青春惊慌失措 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):

    
    
      
        
      
      
        
        
      
    
    

提交回复
热议问题