Execute server-side shell script on button click
Asked Answered
W

1

1

I am trying to execute a shell script that resides in my server. And I need to get the (string) result of this shell script after execution. However, this script should only be triggered only when a certain button in my ReactJS app is pressed.

I spent considerable amount of time looking for answer. So far, all the answers point to an idea of creating a web service then have the app call the service on button click. But none of the answers pointed how exactly this is done nor any of the answers point to any article that discusses this approach. (Sorry if this is a basic approach, but I just learned ReactJS last month from Udemy.)

Would you mind creating a simple code that demonstrates communication between the 'shell script web service' and a button (onClick)? Or at least provide an article link that discusses this approach?

Thanks for any help.

EDIT: What I tried so far is How to execute shell command in Javascript. But comments say that this will not work on browser. I guess this is the code that I need to write in my web service?

Wier answered 28/3, 2022 at 11:48 Comment(0)
W
7

Finally, I got it. Below is what I did.

Step1: create a page/api/execute.js (name your file appropriately)

Step2: put this sample shell script (ls command) in your execute.js

export default function handler(req, res) {
  const execSync = require('child_process').execSync;
  // import { execSync } from 'child_process';  // replace ^ if using ES modules

  const output = execSync('ls', { encoding: 'utf-8' });  // the default is 'buffer'
  const splitted = output.split(/\r?\n/);  
  const filtered = splitted.filter( e => {
    return e !== '';
  });

  res.status(200).json(JSON.stringify(filtered))
}

Step3: In your react component, add a button with onClick handler like so:

<Button primary onClick={this.execCommand}>Execute Shell Command</Button>

Step4: create your execCommand function:

async execCommand() {
    const req = await fetch("/api/execute");
    const data = await req.json();
    console.log(data);
}

Step5: Click your button and see the output on your browser's console.

Cheers!

Wier answered 29/3, 2022 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.