简体   繁体   English

在React中-如何从.sh(Shell Script)文件中获取价值?

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

I have .sh file like : 我有.sh文件,例如:

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. 我想要实现的是从.sh文件获取输出并将其用于我的react应用程序。

I have searched for npm packages but can't find any useful 我已经搜索了npm软件包,但找不到任何有用的软件包

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" 假设您不在Windows计算机上,则可以编写简单的Node Express服务器,该服务器可以接收GET请求,然后使用Node的内置child_process.exec()执行shell脚本,然后发送包含stdout的响应,在这种情况下,将是您的Shell脚本的输出-“ Hello”

Code for the server. 服务器代码。 'static' folder contains index.html and index.js, code for last is below this: “静态”文件夹包含index.html和index.js,last的代码如下:

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 ): 客户端的示例代码(您也可以将React包裹在此代码周围,因为您唯一需要的是在fetch的帮助下制作的XHR):

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请求传递值以作出反应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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