Getting the value from a .sh (Shell Script) file in React: How to do it?

There is a .sh file that contains the following code:

echo "Hello"

This code produces the output:

Hello

The question at hand is:

I am trying to extract the output from the .sh file and integrate it into my React application.

After exploring various npm packages, I have not been able to find one that fits my requirements.

Answer №1

If you're not using a Windows machine, you can create a simple Node Express server to handle GET requests and execute shell scripts using Node's built-in child_process.exec(). The server will then send back the output of the script as a response, which in this case would be "Hello".

Below is the code for the server. The 'static' folder contains index.html and index.js:

const express = require('express')
const { exec } = require('child_process')
const { join } = require('path')

const port = process.env.PORT || 24587
const app = express()

app.use(express.static(join(__dirname, 'static')))

app.get('/hello', (req, res) => {
  exec(join(__dirname, 'hello.sh'), (err, stdout, stderr) => {
    if (err) {
      return res.status(400).json({ output: null, error: err.message })
    }

    res.status(200).json({ output: stdout, error: null })
  })
})

app.listen(port, () => {
  console.log('server listening on port', port)
})

Here is an example code snippet for the client side (you can also use React with this code since it simply makes an XHR request with the help of fetch):

const btn = document.querySelector('#btn') // <button id="btn">get</button>
const result = document.querySelector('#result') // <div id="result"></div>

btn.addEventListener('click', () => {
  if (self.fetch) {
    fetch('/hello')
      .then(res => res.json())
      .then(data => {
        result.innerText = data.output
      })
      .catch(data => {
        result.innerText = data.error
      })
  }
})

Answer №2

Consider saving the output to a file by using either echo $var > $destdir or utilizing sed. Afterwards, you can read this file in nodejs and pass the value through an ajax request to react for further processing.

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

Tips for effectively utilizing a cart collection system

I am currently exploring how to utilize sessions for user tracking and updating my cart collection. Below is the code from my route.js file in an Express and Node application: app.post('/cart/:id', function (req, res) { if (!userKey) { ...

What could be the reason for the malfunctioning dropdown menu in my navigation bar upon clicking it?

After spending hours practicing creating a navbar using Bootstrap 3.3.7, I've hit a roadblock - the dropdown is not working when clicked on. It's frustrating because I have double-checked all my scripts and ensured that I have the latest version ...

acquire the JWToken using Cypress and establish it as the header for subsequent requests

While attempting to test an Express web application I developed, the first step is authentication to retrieve a JWT token. The token retrieval process works fine, but when trying to set the header for subsequent requests, it doesn't seem to work. Thi ...

The comet crash application is experiencing technical difficulties on Ubuntu version 14.01

jayesh@jayesh-VirtualBox:~/meteroapp/leadengine$ sudo npm install -g meteorite [sudo] password for jayesh: npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm http GET https://registry. ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Tips for creating an effective update method in Prisma

I need help fixing my PUT method in Prisma to update all plan connections when updating my checkout this.connection.update({ where: { id }, data: { name, description, picture, updatedAt: new Date(), plans ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Apologies, the package "@jest/environment@^24.5.0" that is needed by "@jest/reporters@^24.5.0" could not be located on the "npm" registry

Recently started learning React Native by following Facebook's tutorial available at https://facebook.github.io/react-native/docs/getting-started using React Native CLI. I successfully created a project yesterday. However, today when I tried to creat ...

React applications leveraging ES6 binding patterns

When examining various React code examples, a common pattern that emerges is the following: class Foo extends Component { constructor() { this.someMethod = this.someMethod.bind(this); } someMethod() { } <Bar doSomething={this.someMetho ...

Sequelize does not automatically include a junction table in the associated model data

Imagine having two models, User and Event, established in a many-to-many relationship with User.belongsToMany(Event) and Event.belongsToMany(User). Everything seems to be functioning properly until executing User.findAndCountAll({include: [{model: Event}]} ...

When attempting to use the node.js REPL over a socket, the connection will unexpectedly terminate if the user presses CTRL + C

As I attempt to utilize REPL over a socket in a manner similar to a telnet connection, I have encountered an issue whereby pressing CTRL + C or CTRL + D, or encountering an error result in the socket connection becoming unresponsive. The code written in n ...

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

Is it possible to configure Express.js to serve after being Webpacked?

I am currently in the process of setting up a system to transpile my Node server (specifically Express) similar to how I handle my client-side scripts, using webpack. The setup for the Express server is quite straightforward. I bring in some node_modules ...

Initiate the Html.BeginForm process in an asynchronous manner

Within my ASP.NET MVC 3 application, I am attempting to upload a file using the Html.BeginForm helper, as shown below: <% using (Html.BeginForm("ImportFile", "Home", new { someId = Id }, FormMethod.Post, new { enctype="multipart/form-data" } )) %> ...

Folding without extending

My button has a div inside it with content. I've set it up so that when the div is clicked, the collapsed content expands. The hover effect changes color and pointer as expected. But for some reason, clicking on the div doesn't expand the content ...

I am looking for a way to showcase buffer data as an image in a React application

Need help with displaying images in a react application? function App() { const [imageData, setImageData] = useState(); useEffect(() => { const fetchData = async () => { const response = await axios.get('http://localhost:8000' ...

Node.JS product creation triggers a Stripe outage

Attempting to create a product in stripe has been problematic for me. Every time I make the call with stripe.products.create(), it causes lag, and shortly after my server crashes due to 'JavaScript heap out of memory'. Here is my approach: impo ...

Attempting to extract a text string from a chunk of HTML code

My goal is to extract a text string (specifically, an article title) from a snippet of HTML code. The title in question reads "Journalist Allegedly Spied on Zoom Meetings of Rivals in Hilariously Dumb Ways." The challenge lies in the fact that the title d ...

Utilize MUI styles on elements that are not originally styled by MUI

I am working on a Gatsby application that utilizes MUI v5 and allows users to input custom markup. I want the user-entered markup to have the same base styles as the corresponding Typography elements (as shown below). How can I make this happen? It is wor ...

Sockets causing a blockage in the Express server

Encountering an issue while setting up an express server with Sockets (using the socketcluster-server module). After sending around 20 http requests, the express server gets blocked, leading to the Sockets (client) reporting a connection depletion. Has an ...