最小的 Websocket Nodejs 尾部示例 [英] Minimum Websocket Nodejs Tail Example

查看:37
本文介绍了最小的 Websocket Nodejs 尾部示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 websocket 为浏览器创建数据流.数据是日志文件的输出.(tail -f 文件名)使用节点 js,我设法登录到 stdout,但我无法创建服务器并创建客户端 (js/html) 代码来创建 websocket 并接收此子进程的所有输出.有人可以帮我吗?

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 服务器输出到 STDOUT 的尾部(如 http://snippets.dzone 中所示.com/posts/show/12067)

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.

推荐答案

这么简单?

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.

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

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.

这篇关于最小的 Websocket Nodejs 尾部示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆