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


im new node.js , question:

for example: got web application , application have button , on button click want run node console command (for example: node socket.io).

so:

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

so in example want start socket.io web javascript file. how ? know basic question want understand how or possible.

edit

but possible run ajax request node command node.js , fire up ("node socket.io")?

im asking because want start , stop socket.io web application, not console command directly.

you need express route 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 , stdout buffers.

you need post command (using ajax or form) /exec. give 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 extremely careful security having though opening access system's console.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -