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

时间:2015-06-02 07:07:37

标签: javascript node.js socket.io sails.js

我是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.

请告知,如果有开源示例,那将会很棒。

提前致谢!

1 个答案:

答案 0 :(得分:2)

嗯,非常简单的代码:最简单的AJAX,没有beaty。举个例子。代码经过测试且完全可行。

<强> 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 Child Process

希望它有所帮助。