簡體   English   中英

sails.js如何構建實時Web控制台應用程序

[英]sails.js how build real time web console app

我是sails.js的新手,我只了解基礎知識,並且能夠構建簡單的MVC應用。 我的樣板應用程序: https : //github.com/JerryYangJin/zero

我想使用sails.js構建實時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,沒有任何缺點。 只是個例子。 代碼已經過測試並且完全可以使用。

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();
  }
};

輸入命令查看 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.js子進程

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM