Skip to content

Instantly share code, notes, and snippets.

@dongyuwei
Created April 13, 2012 04:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dongyuwei/2373701 to your computer and use it in GitHub Desktop.
Save dongyuwei/2373701 to your computer and use it in GitHub Desktop.
nodejs stream tail -f to web browser
var express = require('express'), spawn = require('child_process').spawn;
var app = express.createServer();
app.use(app.router);
var tail;
app.get('/tail', function(req, res) {
res.header('Content-Type','text/html;charset=utf-8');
tail = spawn('tail', ['-f', './test.log']);
tail.stdout.on('data', function(data) {
console.log('stdout: ' + data);
res.write(data, 'utf-8');
});
tail.stderr.on('data', function(data) {
console.log('stderr: ' + data);
res.write(data, 'utf-8');
});
tail.on('exit', function(code) {
console.log('child process exited with code ' + code);
res.end(code);
});
});
app.listen(8080);
console.log('server ' + process.pid + ' running on 8080 port...');
@dongyuwei
Copy link
Author

var http = require('http'), spawn = require('child_process').spawn;
http.createServer(function(req, res) {
if(req.url === '/tail'){
res.header('Content-Type' , 'text/html;charset=utf-8');

tail = spawn('tail', ['-f', './test.log']);
tail.stdout.pipe(res);

}
}).listen(8081);

@dongyuwei
Copy link
Author

nodejs chunked 输出时'Content-Type'头必须有charset,如'Content-Type': 'text/html;charset=utf-8' ,否则浏览器不渲染. 和数据是否有1024字节没有关系,firefox11.0, chrome18.0.1025.162, IE6下测试过

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment