javascriptnode.jsexpresssocket.io

How to execute node (console) command from javascript file on click via ajax


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

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).

So:

$( ".button" ).on( "click", function() {
   //run ajax to node with command for example "node 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.

EDIT

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

Im asking this because I want to start and stop socket.io from web application, not from console command directly.


Solution

  • 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
          })
        }
      })
    
    
    })
    
    ...
    

    note: stderr and stdout are buffers.

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

    Success:

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

    Failure:

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

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