将child_process输出发送到Socket.io

问题描述

我已经构建了一个简单的Express应用,该应用使用child_process来运行命令。然后,我需要使用socket.io发送到浏览器的每一行的输出,以下示例应用程序将部分运行,不同之处在于,一旦命令完成,它将所有输出行以单个字符串发送。

是否可以发送每行并将其呈现在客户端/浏览器中?

//server.ts
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const { exec } = require('child_process');

app.get('/',(req,res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection',(socket) => {
  console.log('a user connected');
  socket.on('disconnect',() => {
    console.log('user disconnected');
  });
  socket.on('chat message',(msg) => {
    console.log('message: ' + msg);
   // io.emit('chat message',msg);
  });
  socket.on('chat message2',(msg) => {
    console.log('message: ' + msg);


    exec("kind create cluster",(error,stdout,stderr) => {
      if (error) {
          console.log(`error: ${error.message}`);
          io.emit('chat message',`error: ${error.message}` );
          return;
      }
      if (stderr) {
          console.log(`stderr: ${stderr}`);
          io.emit('chat message',`error: ${stderr}` );
          return;
      }
      console.log(`stdout: ${stdout}`);
      io.emit('chat message',new Buffer("> "+ `error: ${stdout}` ));

      //ws.send(JSON.stringify({id:"shell",data:{stdout}}),function () {  
        //
        // Ignore errors.
        //
      });
  });

});

http.listen(3000,() => {
  console.log('listening on *:3000');
});

这是客户端代码:

//index.html
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica,Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
      form button { width: 9%; background: rgb(130,224,255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>

  <script src="/socket.io/socket.io.js"></script>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script>
    $(function () {
      var socket = io();
      $('form').submit(function(e){
        e.preventDefault(); // prevents page reloading
        socket.emit('chat message',$('#m').val());
        socket.emit('chat message2',"Message 2 here!!");
        $('#m').val('');
        return false;
      });
      socket.on('chat message',function(msg){
        $('#messages').append($('<li>').text(msg));
      });
    });
  </script>

  <script>
    var socket = io();
  </script>


  </html>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)