簡體   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