本文介绍了如何通过Ajax单击从javascript文件执行node(console)命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是node.js的新手,这是我的问题:

Im new to node.js and this is my question:

例如:我有一个Web应用程序,从该应用程序中有一个按钮,然后单击按钮,我想运行节点控制台命令(例如:node socket.io).

For example: I got web application and from that application I have a button and on button click I want to run node console command (for example: node socket.io).

所以:

$( ".button" ).on( "click", function() {
   //run ajax to node with command for example "node socket.io"
 });

因此,在此示例中,我想从Web javascript文件启动socket.io.怎么做 ?我知道这是一个非常基本的问题,但我想了解如何做到这一点,甚至有可能.

So in this example I want to start socket.io from web javascript file. How to do it ? I know its very basic question but I want to understand how to do it or is it even possible.

编辑

但是是否可以使用该node命令向node.js运行ajax请求,然后启动它("node socket.io")?

But is it possible to run ajax request with that node command to node.js and then fire up it up ("node socket.io")?

我问这个问题是因为我想从Web应用程序而不是直接从控制台命令启动和停止socket.io.

推荐答案

您将需要这样的快速路线:

You would need an express route like this:

...

var exec = require('child_process').exec;

app.post('/exec', function(req, res) {
  var cmd = req.body.command;

  exec(cmd, function(error, stdout, stderr) {
    if (stderr || error) {
      res.json({
        success: false,
        error: stderr || error,
        command: cmd,
        result: null
      })
    } else {
      res.json({
        success: true,
        error: null,
        command: cmd,
        result: stdout
      })
    }
  })


})

...

注释:stderr和stdout是缓冲区.

note: stderr and stdout are buffers.

然后,您需要将POST命令(使用AJAX或表单)发送到/exec.这将给您一个响应,例如:

You then need to POST your command (using AJAX or a form) to /exec. Which will give you a response such as:

成功:

{
  success: true,
  error: null,
  command: "ls",
  result: "app.js bin node_modules package.json public routes views "
}

失败:

{
    success: false,
    error: "/bin/sh: foobar: command not found ",
    command: "foobar",
    result: null
}

在打开对系统控制台的访问权限时,您需要特别小心[strong> .

You need to be extremely careful with security having something like this though as you are opening up access to your system's console.

这篇关于如何通过Ajax单击从javascript文件执行node(console)命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:43