这是我主要从这个要点中获取的一个简单示例
一、切换到一个空目录
mkdir socket-tail-app; cd socket-tail-app;
然后,安装需要的东西
npm install socket.io
像这样运行它
node server.js /path/to/file/to/tail
运行后,打开浏览器
http://localhost:8000
以下是您需要的文件:
服务器.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');
索引.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>