Przykład Minimum Websocket NodeJS Tail
Próbuję utworzyć strumień danych do przeglądarki za pomocą websocket. Dane są wynikiem pliku dziennika. (nazwa pliku tail-f) Używając node js, udało mi się zalogować do stdout, ale nie byłem w stanie utworzyć serwera i utworzyć kod klienta (js/html), aby utworzyć websocket i odebrać wszystkie dane wyjściowe tego procesu potomnego. Czy ktoś może mi pomóc?
Węzeł.Serwer JS wyprowadza ogon na STDOUT (jak widać w 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);
});
Mój celem jest jak najprostszy strumień. Każde inne proste rozwiązanie jest dobrze przyjęte. Dzięki.
3 answers
To proste?
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);
Połącz się z serwerem, a dostaniesz ogon. Będziesz musiał uważać na timeouty po stronie klienta, w zależności od przeglądarki, jeśli ogon pójdzie bezczynnie.
Jeśli chcesz uzyskać dostęp do tych danych z javascript w przeglądarce, rozważ użycie socket.io ponieważ użyje to najlepszej metody dostępnej przeglądarce, aby uzyskać dostęp do strumienia (websocket, long poll, flash itp.). Jeśli potrzebujesz przykład javascript klienta, mogę to też opublikować.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-05 14:56:39
To wydaje się być stare pytanie i bardzo możliwe, że problem jest już rozwiązany, ale gdyby go tu nie było to gist https://gist.github.com/867575 .
Używa socket.io i zamiast tarła procesów "tail-f" (co zajmuje więcej pamięci), fs.używany jest watchFile.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-13 01:23:41
Oto prosta próbka, którą głównie wziąłem z tego GISTA
Najpierw przełącz się do pustego katalogu
mkdir socket-tail-app; cd socket-tail-app;
Następnie zainstaluj to, co jest potrzebne
npm install socket.io
Uruchom to tak
node server.js /path/to/file/to/tail
Po uruchomieniu otwórz przeglądarkę na
http://localhost:8000
Oto pliki, których potrzebujesz:
Serwer.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');
Indeks.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>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-16 13:16:00