Click the button to run a server-side shell script

I have a task where I need to run a shell script on my server and retrieve the resulting string after execution. The condition is that this script should only run when a specific button in my ReactJS application is clicked.

After spending a considerable amount of time searching for answers, I found suggestions to create a web service and call it from the app upon button click. However, none of the responses gave detailed instructions on how to implement this or provided any related articles for further understanding. (I apologize if this seems like a basic concept, as I only started learning ReactJS recently through an online course.)

Could someone perhaps provide a simple code snippet demonstrating how to establish communication between the 'shell script web service' and a button click event? Alternatively, sharing a relevant article link discussing this approach would also be greatly appreciated.

Thank you in advance for any assistance.

EDIT: In my search efforts, I came across a query on How to execute shell command in Javascript. However, based on the comments, it appears that this method may not function properly in a browser environment. Is this the kind of code I should include in my web service?

Answer №1

Finally, success! Here's what I did.

Step1: Begin by creating a page/api/execute.js (name your file appropriately).

Step2: Insert the following sample shell script (ls command) into your execute.js file:

export default function handler(req, res) {
  const execSync = require('child_process').execSync;
  
  const output = execSync('ls', { encoding: 'utf-8' });
  const splitted = output.split(/\r?\n/);  
  const filtered = splitted.filter( e => {
    return e !== '';
  });

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

Step3: Within your react component, include a button with an onClick handler like this:

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

Step4: Create your execCommand function as follows:

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

Step5: Click the button and view the output in your browser's console.

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I would like to know how to modify the style of an MUI button in ReactJS when it is clicked

I am attempting to modify the appearance of a button upon clicking it in ReactJS. However, I am facing challenges as the standard CSS method of altering a button's behavior does not seem to work. My goal is to change the background color of the button ...

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

Wrapper class for iOS and Android libraries in React-Native

Currently, I am exploring React Native and aiming to develop a unified interface (wrapper) for two libraries with similar functionalities but tailored for different platforms. For instance, DatePickerIOS & react-native-wheel-picker-android. I've expe ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

When the application is converted into static files, the dynamic routes fail to function properly

I have a website that is statically exported but has dynamic routes. During development, the site works fine. However, when I build and export it, then serve the static files using serve, an issue arises. If you go to the site root and click on a link th ...

Experiencing Problems with Routing React page on Apache2 Server

I'm encountering difficulties accessing routes other than the homepage on my React website, which is currently hosted on an Apache2 web server. You can find the page here: www.TJBrackett.com After attempting to add a .htaccess file to the directory ...

Formik React struggling with error management and handling tasks accurately

I am currently using the Formik template to develop a Login Form. onSubmit={( values, { setSubmitting, setErrors /* setValues and other goodies */ } ) => { props.logMeIn(va ...

React and Express facing CORS header challenge

I'm facing an issue with CORS despite trying various solutions found on Stack Overflow. My app uses Express/NodeJS as an API and React JS for the frontend. During development, the React app at http://localhost:3000 communicates successfully with the ...

The command "react-scripts" couldn't be located in the current environment

Currently enrolled in a Udemy course that involves using create-react-app. However, I encounter an error when attempting to run npm start and/or yarn start. You can find the course here: Complete React Developer in 2020 (w: Redux, Hooks, GraphQL) To init ...

Error Encountered: SyntaxError due to an Unexpected token < found in JSON at position 0

I am struggling to retrieve data from a local asp.net API running on https://localhost:44388/. When attempting to make a GET request, it returns HTML instead of JSON. There are two possible reasons for this issue: 1. Typo in the URL (I have verified in m ...

Trouble arises with Service Workers during the transition from Create React App to Next JS

After transitioning our landing page from create-react-app to Next.js, we encountered an issue with users receiving a cached version of the old website. This is due to the default service worker that was registered on their browsers when using create-react ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Issue with TypeScript when using destructuring on an object

When attempting to destructure data from an object, I encountered the error message Property XXXX does not exist on type unknown. This issue arose while using React Router to retrieve data. let {decoded, reasonTypes, submissionDetails} = useRouteLoaderDa ...

What is the best way to utilize the forEach method in React to manipulate a navigation element containing multiple links?

Here is the code I'm trying to convert: document.addEventListener("scroll", function() { const links = document.querySelectorAll(".nav-link"); for (const l of links) l.classList.toggle('scrolling', window.scrollY &g ...

I am looking to export multiple 'Pure components'

Currently, I am developing an app using React Native and came across an unusual observation. For some reason, the following code throws an error unless I modify the last sentence to: export default MyButton3; I aim to export more than one pure component ...

The property 'currentUser' of 'Object(...)(...)' is unable to be destructured due to its null value

I keep encountering the error message "Cannot destructure property 'currentUser' of 'Object(...)(...)' as it is null" whenever I utilize the useContext() hook from React in my Next.js project. // Other imports import CurrentUserContext ...

Revamp State before redirecting using React Router Dom

In my current project, I am facing an issue with redirecting after updating the state successfully. The technologies I'm using include React 16.12.0 and React Router DOM 5.1.2. Here's the scenario: I have a button that, when clicked, should updat ...

What is the best method to implement real-time data updates in a single page application

Looking for a solution to update the data in my SPA web app that utilizes next js and express js. How can I ensure the application on computer 1 reflects changes made by computer 2 without requiring a manual refresh? ...

Issues with displaying characters in React when using UTF-8 encoding

When utilizing the Material-UI kit for React, I've encountered an issue post-build where UTF-8 character set does not display correctly. Instead of displaying characters like 'Ş, Ü, ö, Ç, ç', it shows a question mark symbol '?&apo ...

Interactive Tab Navigation using React Swipe

As a new user of React, I am exploring ways to implement swipeable tabs for mobile browsers (similar to Instagram's profile tabs). After some research, I came across react-swipeable-views and Material UI, which I tried using. While it seems to be fu ...