简体   繁体   中英

In React - How to get value from .sh(Shell Script) file?

I have .sh file like :

echo "Hello"

Which outputs :

Hello

Here is the query :

What I want to achieve is, to get output from the .sh file and use it in my react application.

I have searched for npm packages but can't find any useful

Assuming you are not on Windows machine, you can write simple Node Express server, which can receive GET request, then execute your shell script with Node's built-in child_process.exec() and then send response containing stdout, which, in this case, will be your shell script's output - "Hello"

Code for the server. 'static' folder contains index.html and index.js, code for last is below this:

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)
})

Example code for the client (you can also wrap React around this code because the only thing you need is XHR made here 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
      })
  }
})

我认为您应该将输出放置到任何文件( echo $var > $destdir或使用sed ),使用nodejs读取此文件,例如通过ajax请求传递值以作出反应。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM