繁体   English   中英

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

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

我有.sh文件,例如:

echo "Hello"

哪个输出:

Hello

这是查询:

我想要实现的是从.sh文件获取输出并将其用于我的react应用程序。

我已经搜索了npm软件包,但找不到任何有用的软件包

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

服务器代码。 “静态”文件夹包含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)
})

客户端的示例代码(您也可以将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