sails.js如何构build实时的Web控制台应用程序

我是sails.js的新手,我只知道基础知识,能够构build简单的MVC应用程序。 我的样板应用程序: https : //github.com/JerryYangJin/zero

我想用sails.js来构build一个实时的Web控制台应用程序。

该应用程序是这样工作的:

1. user types command in web browser 2. sails(socket.io) to call a native console program on the server, using user typed command as STDIN 3. sails(socket.io) to get native console program output from STDOUT then send it back to user. 

请指教,如果有开源的例子,这将是非常好的。

提前致谢!

那么,非常简单的代码:最简单的AJAX,没有beaty。 只是例子。 代码已经过testing,完全可行。

API /控制器/ CliController.js

 module.exports = { /** * Command execution * @param {String} req.body.command [command ro execute] * @return {JSON} [result or error] */ run: function (req, res) { // Check for valid command string in request if (req.body === undefined || !req.body.command || req.body.command.trim().length === 0){ return res.redirect('/cli/enter'); } // Split string to array as `child_process` needs array var command = req.body.command.split(" "), err = [], result = ""; // Get needed module and execute command var spawn = require('child_process').spawn, run = spawn(command.splice(0, 1)[0], command); run.stdout.on('data', function (data) { result = result + data.toString(); }); run.stderr.on('data', function (data) { err.push(data.toString()); console.log(data); }); run.on('error', function (error) { err.push(error.toString()); console.log(error); run.stdin.end(); }); run.on('close', function (code) { if (code !== 0) { err.push('ps process exited with code ' + code); } run.stdin.end(); // Return error if (err.length > 0){ res.status(500); return res.json({errors: err}); } //Return data return res.ok(result); }); }, /** * Simple function to render view with command line */ enter: function(req, res){ return res.view(); } }; 

input命令视图 views / cli / enter.ejs

 <input type="text" name="command" id="command"/> <button id="sendCommand">Execute</button> <pre id="result"></pre> <script type="text/javascript"> $('#sendCommand').click(function(){ var command = $('#command').val().trim(); if (command.length > 0){ io.socket.post('/cli/run', {command: command}, function(data, jwr){ if (jwr.statusCode == 200){ $('#result').text(data); } else { $('#result').text('ERROR: ' + jwr.statusCode + JSON.stringify(data.errors)); } }); } }); </script> 

当然你必须考虑安全性。

我在示例中使用Node.jssubprocess 。

希望能帮助到你。