【问题标题】:How to execute sh script or shell commands from browser input using a node server?如何使用节点服务器从浏览器输入执行 sh 脚本或 shell 命令?
【发布时间】:2020-07-11 16:58:22
【问题描述】:

我正在尝试从 Web 界面重新启动或关闭 Raspberry Pi。我过去使用 PHP 的 shell_exec 管理过这个问题。
这一次我尝试只使用JavaScript
对于前端,我选择了VueJS。对于后端,我不知道该选择什么;我见过NodeJSExpress JS 以及更多能够在 UNIX 操作系统设备(例如 Raspberry Pi)上运行的服务器。
我已经设法使用child_process 并使用node ./test.js 从测试文件运行shell 命令,但我该如何整体做到这一点?

如何将 Restart Button 从 Vue 链接到节点或 Express 服务器

这是我用来测试的 Vue 组件。它包含一个输入,而不是一个按钮,只是为了测试简单的 shell 命令。

<template>
  <div id="wrapper">
    <div class="input_row">
      <input type="text" class="input_text" id="shell" v-model="shell_command" />
      <label class="label_" for="shell">Type Shell Command</label>
    </div>
    <button type="button" class="button" @click="shellExec">Submit !</button>
  </div>
</template>

<script>
import { exec } from "child_process";

export default {
  name: "ShellExec",
  components: {},
  data() {
    return {
      shell_command: ""
    };
  },
  methods: {
    async shell() {
      return new Promise((resolve, reject) => {
        exec(this.shell_command, (err, stdout, stderr) => {
          if (err) {
            reject(err);
          } else {
            resolve({ stdout, stderr });
          }
        });
      });
    },

    async shellExec() {
      let { stdout } = await this.shell();
      for (let line of stdout.split("\n")) {
        console.log(`ls: ${line}`);
      }
    }
  }
};
</script>

<style scoped>
</style>

我还没有决定服务器,但我看到了一些 Express 服务器的例子。

【问题讨论】:

    标签: javascript node.js express vue.js


    【解决方案1】:

    child_process 是一个 node.js 库,在浏览器中不可用。您可以将您的应用程序转换为可以将其配置为可用的电子应用程序(并且仅在您正在执行的主机上使用),或者设置您的应用程序可用于触发命令的 API。

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2017-09-26
      • 2023-03-28
      • 2020-01-16
      相关资源
      最近更新 更多