最小 Websocket Nodejs 尾部示例

发布于 2024-09-14 14:47:28 字数 703 浏览 6 评论 0原文

我正在尝试使用 websocket 创建到浏览器的数据流。数据是日志文件的输出。 (tail -f 文件名) 使用 Node js,我已经成功登录到 stdout,但我无法创建服务器并创建客户端(js/html)代码来创建 websocket 并接收该子进程的所有输出。 谁能帮助我吗?

NODE.JS 服务器将尾部输出到 STDOUT(如 http://snippets.dzone.com/posts 中所示) /show/12067

var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];

if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);
sys.puts("start tailing");

tail.stdout.on("data", function (data) {
  sys.puts(data);
});

我的目标是拥有尽可能简单的流。任何其他简单的解决方案都会受到欢迎。谢谢。

I'm trying to create a stream of data to the browser using websocket. The data is the output of a log file. (tail -f filename)
Using node js, I've manage to log into stdout, but I haven't been able to create the server and create the client (js/html) code to create a websocket and receive all the output of this child process.
Can anyone help me?

NODE.JS SERVER OUTPUTTING TAIL TO STDOUT (as seen in http://snippets.dzone.com/posts/show/12067)

var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];

if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);
sys.puts("start tailing");

tail.stdout.on("data", function (data) {
  sys.puts(data);
});

My goal is to have the simplest stream possible. Any other simple solution is well received for this. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

从﹋此江山别 2024-09-21 14:47:28

就这么简单吗?

var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];
if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);

http = require('http');
http.createServer(function (req, res) {
  sys.puts("new connection..");
  res.writeHead(200, {'Content-Type': "text/plain;charset=UTF-8"});
  tail.stdout.on("data", function (data) {
    res.write(data);
  }); 
}).listen(3000);

连接到服务器,你就会得到你的尾巴。如果尾部空闲,您必须注意客户端的超时情况,具体取决于您的浏览器。

如果您想在浏览器中通过 JavaScript 访问此数据,请考虑使用 socket.io 因为这将使用最佳方法浏览器可用于访问流(websocket、长轮询、flash 等)。如果您需要客户端 javascript 示例,我也可以发布它。

This simple?

var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.ARGV[2];
if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

var tail = spawn("tail", ["-f", filename]);

http = require('http');
http.createServer(function (req, res) {
  sys.puts("new connection..");
  res.writeHead(200, {'Content-Type': "text/plain;charset=UTF-8"});
  tail.stdout.on("data", function (data) {
    res.write(data);
  }); 
}).listen(3000);

Connect to the server and you'll get your tail. You'll have to watch for timeouts on the client side, depending on your browser, if the tail goes idle.

If you want to access this data from javascript within the browser, consider using socket.io as this will use the best method the browser has available to access the stream (websocket, long poll, flash etc.). If you need a client javascript example, I can post that too.

陪你到最终 2024-09-21 14:47:28

这似乎是一个老问题&很可能问题已经解决了
但如果它不存在,这里有一个要点 https://gist.github.com/867575

它使用socket.io
并且不使用“tail -f”进程(这会占用更多内存),而是使用 fs.watchFile 。

This seems like an old question & very possibly the problem is already solved,
but in case it isn't here is a gist https://gist.github.com/867575 .

it uses socket.io
and instead of spawning "tail -f" processes(which takes more memory), fs.watchFile is used.

身边 2024-09-21 14:47:28

这是一个简单的示例,我主要是从 this gist

首先,切换到一个空目录

mkdir socket-tail-app; cd socket-tail-app;

然后,安装需要

npm install socket.io               

像这样运行它

node server.js /path/to/file/to/tail

运行后,打开浏览器,

http://localhost:8000

这里是您需要的文件:

server.js

var http    = require('http'),
    io      = require('socket.io'),
    fs      = require('fs');

var spawn = require('child_process').spawn;

var filename = process.argv[2];
if (!filename) 
{
  console.log("Usage: node server.js filename_to_tail");
  return;
}


// -- Node.js Server ----------------------------------------------------------

server = http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/html'})
  fs.readFile(__dirname + '/index.html', function(err, data){
    res.write(data, 'utf8');
    res.end();
  });
})
server.listen(8000, '0.0.0.0');

// -- Setup Socket.IO ---------------------------------------------------------

var io = io.listen(server);

io.on('connection', function(client){
  console.log('Client connected');
  var tail = spawn("tail", ["-f", filename]);
  client.send( { filename : filename } );

  tail.stdout.on("data", function (data) {
    console.log(data.toString('utf-8'))
    client.send( { tail : data.toString('utf-8') } )
  }); 

});

console.log('Server running at http://0.0.0.0:8000/, connect with a browser to see tail output');

index.html

<!DOCTYPE html>
<html>
<head>
  <title>tail.js</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="//cdn.socket.io/socket.io-1.3.7.js"></script>

  <style>
    body
      { color: #1a2c37;
        font-family: 'Helvetica', sans-serif; font-size: 86%;
        padding: 2em; }
    #info
      { font-size: 120%;
        font-weight: bold; }
    #tail
      { border: 1px solid #ccc;
        height: 300px;
        padding: 0.5em;
        overflow: hidden;
        position: relative;
        overflow-y: scroll; }
  </style>

</head>
<body>
  <pre id="info"></pre>
  <pre id="tail"></pre>

  <script>

  var Application = function() {


    var socket = io.connect('http://127.0.0.1:8000/');

    socket.on('connect', function() {
      console.log('Connected to:', socket.host);
    });
    socket.on('message', function(message) {
      console.log('Received message:', message);
      if (message.filename) {
        $('#info').html( '$ tail -f ' + message.filename );
      };
      if (message.tail) {
        $('#tail').html( $('#tail').html() + message.tail );
        bottom = $("#tail")[0].scrollHeight - $("#tail").height()
        $('#tail').scrollTop(bottom);

      }
    });

    return {
      socket : socket
    };
  };

  $(function() { var app = Application(); });

  </script>

</body>
</html>

Here's a simple sample I mostly grabbed from this gist

First, switch into an empty directory

mkdir socket-tail-app; cd socket-tail-app;

Then, install what's needed

npm install socket.io               

Run it like this

node server.js /path/to/file/to/tail

After it's running, open a browser at

http://localhost:8000

Here are the files you need:

server.js

var http    = require('http'),
    io      = require('socket.io'),
    fs      = require('fs');

var spawn = require('child_process').spawn;

var filename = process.argv[2];
if (!filename) 
{
  console.log("Usage: node server.js filename_to_tail");
  return;
}


// -- Node.js Server ----------------------------------------------------------

server = http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/html'})
  fs.readFile(__dirname + '/index.html', function(err, data){
    res.write(data, 'utf8');
    res.end();
  });
})
server.listen(8000, '0.0.0.0');

// -- Setup Socket.IO ---------------------------------------------------------

var io = io.listen(server);

io.on('connection', function(client){
  console.log('Client connected');
  var tail = spawn("tail", ["-f", filename]);
  client.send( { filename : filename } );

  tail.stdout.on("data", function (data) {
    console.log(data.toString('utf-8'))
    client.send( { tail : data.toString('utf-8') } )
  }); 

});

console.log('Server running at http://0.0.0.0:8000/, connect with a browser to see tail output');

index.html

<!DOCTYPE html>
<html>
<head>
  <title>tail.js</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="//cdn.socket.io/socket.io-1.3.7.js"></script>

  <style>
    body
      { color: #1a2c37;
        font-family: 'Helvetica', sans-serif; font-size: 86%;
        padding: 2em; }
    #info
      { font-size: 120%;
        font-weight: bold; }
    #tail
      { border: 1px solid #ccc;
        height: 300px;
        padding: 0.5em;
        overflow: hidden;
        position: relative;
        overflow-y: scroll; }
  </style>

</head>
<body>
  <pre id="info"></pre>
  <pre id="tail"></pre>

  <script>

  var Application = function() {


    var socket = io.connect('http://127.0.0.1:8000/');

    socket.on('connect', function() {
      console.log('Connected to:', socket.host);
    });
    socket.on('message', function(message) {
      console.log('Received message:', message);
      if (message.filename) {
        $('#info').html( '$ tail -f ' + message.filename );
      };
      if (message.tail) {
        $('#tail').html( $('#tail').html() + message.tail );
        bottom = $("#tail")[0].scrollHeight - $("#tail").height()
        $('#tail').scrollTop(bottom);

      }
    });

    return {
      socket : socket
    };
  };

  $(function() { var app = Application(); });

  </script>

</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文