【问题标题】:Style output from a nodeJS child_process in htmlhtml中nodeJS child_process的样式输出
【发布时间】:2016-07-27 16:20:46
【问题描述】:

我刚刚开始学习 nodeJS,现在我在理解如何在 html/css 中设置 child_process 的输出样式时遇到了一些麻烦。

到目前为止,我有以下代码:

#!/usr/local/bin/node

var express = require('express');
var app = express();
var fs = require('fs');
var govSh = './../sh/govc.sh';
var util = require('util');
var spawn = require('child_process').spawn;
var PORT = 3333;

if (!fs.existsSync(govSh)) {
    console.log("can't find govc script");
    process.exit(1);
};
app.get('/vmlist', function(req, res) {
    var invPath = spawn(govSh, ['vmlist']);
    invPath.stdout.pipe(res);
});

app.listen(PORT, function() {
    console.log("app will listen on port 3333");
});

当我对http://127.0.0.1:3333/vmlist 进行请求时,我会在浏览器中看到这个:

{"name":"centos1", "state":"poweredOff", "ram":"1", "vcpu":"1", "ip4":""}
{"name":"centos2", "state":"poweredOff", "ram":"8", "vcpu":"2", "ip4":""}

我怎么可能在 html 中使用它并用 css 设置它的样式?或者如何将其发送到客户端 jQuery / Ajax?

编辑:

现在看起来,govc.sh 脚本将像上面一样输出。但这对我来说不是必需的,我只想使用 html 中的输出并设置它的样式。在 govc.sh 脚本中,它与 printf 一起使用 for 循环输出信息:

printf '{"name":"%s", "state":"%s", "ram":"%s", "vcpu":"%s", "ip4":"%s"}\n' ${name} ${vmState} ${vmRam} ${vmCpu} ${vmIp4} 

如果它使 nodejs/javasript 中的事情变得更容易,我可以更改它。

【问题讨论】:

  • 为什么投反对票?如果我应该更改某些内容,请告诉我。

标签: javascript html css node.js express


【解决方案1】:

要呈现为正常页面您必须使用 ejs、jade 模板或输出 html 文件(如本例所示),然后使用 jquery 等从输出的 html 调用 api。

服务器端代码示例

var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var util = require('util');
var execFile = require('child_process').execFile;
var PORT = 3333;

app.use('/assets', express.static('assets')); // create folder "static" relative to this app file and put Your css, js files inside assets

// put index.html file to relative to this file
app.route('/')
  .all(function(req, res) {
    res.sendFile(path.join(__dirname, 'index.html'));
  });

app.route('/vmlist') 
    .get(function(req, res) {
      execFile('./../sh/govc.sh', ['vmlist'], function(err, output) {
          if (err) {
            return res.status(500).send(err);
          }

          // I saw in Your question that application returns 2 json objects 
          // that are an object per line without object delimiter 
          // and array [] chars that will not well handled, 
          // so I'm recreating proper json objects array 
          output = output.split("\n");
          var response = [];
          for(var o in output) {
            var line = output[0].replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); // trimming
            if(line != '') {
              response.push(JSON.parse(line));
            }
          }

          res.json(response); // responding with application/json headers and json objects in it
      });
    });

app.listen(PORT, function() {
    console.log("app will listen on port 3333");
});

客户端(index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/assets/css/common.css">
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script>
      $(function() {
        function getVMS() {
          $.get('http://127.0.0.1:3333/vmlist',  {},  function(vms) {
            var html = '';
            for(var v in vms) {
              var vm = vms[v];
              html+= '<div class="cpu">';
              html+= 'Name: '+vm.name+'<br/>';
              html+= 'State: '+vm.state+'<br/>';
              html+= 'RAM: '+vm.ram+'<br/>';
              html+= 'IPv4: '+vm.ip4+'<br/>';
              html+= '</div>';
            }

            $('#vmlist').html(html);
          });
        }

        getVMS(); // initially getting VMS
        setInterval(getVMS, 10000); // getting VMS continuously every 10 second 
      });
    </script>
</head>
<body>

  <div id="vmlist"></div>

</body>
</html>



文件结构:


附言从 vmlist 正确响应可能存在问题(因为输出格式)。如果它不起作用,请从控制台执行“govc.sh”并在评论中给我它的输出。

【讨论】:

  • 嗨!我将代码更改为此,但现在当我在浏览器中请求 http://&lt;ip&gt;/index.html 时,它会将我重定向到 http://&lt;ip&gt;:3333/vmlist 并让我下载它。我还用更多信息更新了我的问题。
  • 抱歉,我的意思是当我请求 http://&lt;ip&gt;:3333 时。我让我下载一个空白页。
  • 你用我写的内容创建了 index.html 吗?
  • @krt 修复了服务器端问题,再试一次我的回答
  • 哦,是的,现在效果很好。我稍微更改了代码,但你让我走上了正确的道路。谢谢老哥!
猜你喜欢
  • 1970-01-01
  • 2021-09-08
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
相关资源
最近更新 更多